01.字符串常用方法
1.1 find方法
作用:find方法可以在一个较长的字符串中查找子串,他返回子串所在位置的最左端索引,如果没有找到则返回-1
a = 'abcdefghijk'
print(a.find('abc'))
print(a.find('abc',10,100))
1.2 join方法
作用:join方法是非常重要的字符串方法,他是split方法的逆方法,用来连接序列中的元素,并且需要被连接的元素都必须是字符串。
a = ['1','2','3']
print('+'.join(a))
1.3 split方法
作用:这是一个非常重要的字符串,它是join的逆方法,用来将字符串分割成序列
print('1+2+3+4'.split('+')) #the result : ['1', '2', '3', '4']
1.4 strip
作用:strip 方法返回去除首位空格(不包括内部)的字符串
print(" test test ".strip())
1.5 replace
作用:replace方法返回某字符串所有匹配项均被替换之后得到字符串
print("This is a test".replace('is','is_test'))
1.6 首字母大写
>>> s = 'aBdkndfkFFD'
>>> s.capitalize()
'Abdkndfkffd'
1.7 Pinyin 模块,将汉字转换成拼音
from xpinyin import Pinyin
while True:
p = Pinyin()
fullname = raw_input('name:').strip()
fullname = fullname.decode('utf8')
print fullname
xin = fullname[0]
ming = fullname[1:]
name = ming + '.' + xin
username = p.get_pinyin(name, '')
print username
print username + '@yiducloud.cn'
02.字符串格式化
2.1 使用百分号(%)字符串格式化
num = 100
print("%d to hex is %x" %(num, num))
print("%d to hex is %#x" %(num, num)) #100 to hex is 0x64
print("{0} is {1} years old".format("tom", 28))
print("{} is {} years old".format("tom", 28))
print("Hi, {0}! {0} is {1} years old".format("tom", 28))
print("{name} is {age} years old".format(name = "tom", age = 28))
li = ["tom", 28]
print("{0[0]} is {0[1]} years old".format(li))