eg1:open('c:\temp\tex.t','a+')报错:因为没有加r,\t会被当做转义字符(制表符)
改进如下:
open('c:\\temp\\tex.t','a+') 或者------两个斜杠
open(r'c:\temp\tex.t','a+')------------r代表原始字符串,关闭转义机制
字符串的基本操作
1, + 连接
2, * 重复
3, s[i] 索引index
4, s[i:j] 切片slice
5, for循环遍历
###############
1,连接 + 前后连个对象必须都是字符串(如果是其他类型,需要转换)str()、int()、float()
eg1:
>>> s1="www.baidu.com"
>>> s2="ronbin"
>>> print s1,s2
www.baidu.com ronbin---------逗号,在同一行输出,逗号默认的输出就是空格
>>> s3=s1+s2
>>> print s3
<a href="http://blog.51cto.com/tenderrain/1621297">www.baidu.comronbin----------完整连接</a>
eg2:
>>> i=12
>>> s1="times"
>>> print i+s1--------------类型不同无法直接连接
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> print str(i)+s1
12times
>>> print str(i)+' '+s1
12 times
2,重复 *
>>> list1=[1]*5
>>> list1
[1, 1, 1, 1, 1]
>>> list2=[1,'3',67.09]*3-------相当于3个列表做的连接(将列表扩大了3倍)
>>> list2
[1, '3', 67.09, 1, '3', 67.09, 1, '3', 67.09]
>>> s='a'
>>> s1=s+s+s+s
>>> s1
'aaaa'
>>> s1=s*4
>>> s1='a'*4
当需要连接的字符串相同时, * <======> n个+
3,索引
>>> s2='abcdefd'
>>> ch=s2[3]----------[3]被称之为索引index,index从下标为0 开始
>>> ch
'd'
方法:string_name[index]
4,切片
方法:string_name[start_index:stop_index]
start_index:要取字符串的首字母的index
stop_index:要取字符串的尾字母的index+1
>>> sub=s2[1:5]
>>> sub
'bcde'
start_index省略,则从开始切
>>> sub=s2[:5]
'abcde'
stop_index省略,则切到最后
>>> sub=s2[1:]
'bcdefd'
start_index和stop_index都省略,则全切(又相当于没切)
>>> sub=s2[:]
'abcdefd'
start_index和stop_index可以是负数
-1代表最后一位,-2代表倒数第二位,以此类推
>>> s2[5]
'f'
>>> s2[-2]
>>> s2[-4:-1]
'def'
>>> s2[-4:]
'defd'
start_index < stop_index ----> ok step:正数 or 负数
>>> s2[1:4]
'bcd'
>>> s2[4:1]
''-------空值
>>> s2[-1:-4]
''--------空值
string[i:j:step]
step:切的时候顺序往后加1还是顺序往前减1,即空值了方向(默认step=1)
>>> s2[-1:-4:-1]
'dfe'
>>> s2[4:1:-1]
'edc'
i<j step正数
i>j step负数
eg:实现字符串的逆序输出
>>> s='www.baidu.com'
>>> s[-1::-1] -------ok,默认到方向的终点
'moc.udiab.www'
>>> s[-1:0:-1]--------no,少一个字母
'moc.udiab.ww
5,for循环遍历字符串
>>> print s[0]
w
>>> print s[1]
>>> print s[2]
>>> print s[3]
.
>>> for ch in s:---每次循环将s中的字符赋给ch
... print ch---如果加逗号则是统一行输出
...
b
a
i
d
u
c
o
m
>>> for ch in s:
... print ch,
w w w . b a i d u . c o m----同一行输出
本文转自Tenderrain 51CTO博客,原文链接:,http://blog.51cto.com/tenderrain/1621297如需转载请自行联系原作者