玩命加载中...
### 7. 去处字符串头尾的空格 `new_str = my_str.strip()`可用来去除`my_str`头尾的所有空格。 `new_str = my_str.lstrip()`可用来去除`my_str`头部的所有空格。 `new_str = my_str.rstrip()`可用来去除`my_str`尾部的所有空格。 ```python str_1 = ' two spaces in the front and three spaces in the end ' print str_1 # 去除头部的空格 str_2 = str_1.lstrip() print str_2 # 去除尾部的空格 str_3 = str_1.rstrip() print str_3 # 去除头尾的空格 str_4 = str_1.strip() print str_4 ``` ### 8. 在字符串中插入变量 Python中通过`%s`在字符串中插入变量。`my_str = 'this value is %s.'%(my_var)`(`%`的用法较多,这里不做展开介绍)。 例子如下: ```python #例子 x = 5 sentence = "There are %s apples."%x print sentence #也可以插入多个变量。 a, b = 2, 3 c = a + b result = "%s + %s = %s"%(a, b, c) print result ``` ### 9. 字符大小写转换 `new_str = my_str.lower()`可以将得到小写字符串。 `new_str = my_str.upper()`可以将得到大写字符串。 ```python my_str = 'Hello SofaSofa!' print my_str lower_str = my_str.lower() print lower_str upper_str = my_str.upper() print upper_str ``` ### 10. 在字符串中插入回车换行、制表符等特殊符号。 `\n`表示回车(换行)。 `\t`表示制表符(tab)。 ```python #例子 apples = 5 pears = 15 sentence = "There are %s apples.\nThere are %s pears."%(apples, pears) print sentence ``` 小练习。打印九九乘法表。 ```python table = '' for i in range(10): for j in range(1, i + 1): table += '%s*%s=%s \t'%(i, j, i * j) table += '\n' print table ``` 1*1=1 2*1=2 2*2=4 3*1=3 3*2=6 3*3=9 4*1=4 4*2=8 4*3=12 4*4=16 5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81 <ul class="pagination"> <li><a href="index.php">第1页</a></li> <li><a href="2.php">第2页</a></li> <li><a href="3.php">第3页</a></li> <li class="active"><a href="#">第4页</a></li> </ul> <ul class="pager"> <li class="previous"><a href="3.php" ><b>&larr; 返回前一页</b></a></li> <li class="next"><a href="../../tutorials.php"><b><i class="fa fa-graduation-cap" aria-hidden="true"></i>&nbsp; 学完咯!</b></a></li> </ul>