基本操作
字符串格式化
>>> s9="12345 %s"
>>> s9 %"67"
'12345 67'
类似于c语言中的字符串输出方法
可以使用元组中元素一一填充原来字符串中的元素
>>> s10="123%s%s%s"
>>> list1=("1","2","3")
>>> s10 %list1
'123123'
常用方法
1.find:查找指定的子串
查找到返回0,没有制定子串返回-1
>>> s1="12345"
>>> s1.find("12")
0
>>> s1.find("dede")
-1
2.split:根据指定规则分割字符串成多个序列元素
>>> s2="1=2=3"
>>> s2.split("=")
['1', '2', '3']
3.join:功能和split相反,根据指定的规则连接多个序列元素
注意:被连接的序列元素必须都是字符串
>>> s3="1"
>>> s4=[1,2]
>>> s3.join(s4)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
s3.join(s4)
TypeError: sequence item 0: expected string, int found
>>> s4=["11","22"]
>>> s3.join(s4)
'11122'
4.replace:将字符串中的子串替换为指定字符串
此操作不改变原字符串本身,只相当于生成了临时的新的字符串
>>> s5="hello world"
>>> s5.replace("world","tom")
'hello tom'
>>> s5
'hello world'
5.translate:作用类似replace,也是替换字符串,但是是按照字符一一替换
本身有一张包含256个字符的替换表,使用这个方法实际是调用字符替换表,所以不是简单的使用方法,需要修改替换表,这里调用字符串自带的maketrans方法修改替换表
>>> s6="hello"
>>> from string import maketrans
>>> table=maketrans("he","op")
>>> s6.translate(table)
'opllo'
6.lower:返回字符串的字符小写形式
>>> s7="HELLOworld"
>>> s7.lower()
'helloworld'
7.strip:去除字符串首尾的空格
>>> s8=" hello world "
>>> s8.strip()
'hello world'
参考书目:Python基础教程,Magnus Lie Hetland(挪威)。