字符串的格式化 >>> CHA = 123 >>> a = 'test' >>> print('My name is %s' % a) My name is test >>> print('I am %d years old'% CHA) I am 123 years old format_string % (string_to_convert1,string_to_convert2) >>> 'My name is %s and I am %d years old' % (a,CHA) 'My name is test and I am 123 years old' %s 将值转化为str()函数表达的字符串; %d 将值转化为十进制数; %c 将值转化为单个字符; %r 将值转化为repr()函数表达的字符串; 字符串内置函数: capitalize() 将字符串中第一个字符转换为大写
>>> a = 'hahah'
>>> a.capitalize()
'Hahah'
find('str') 检查字符串中是否包含str,找不到返回-1;
>>> a = 'My name is haha'
>>> a.find('name')
3
>>> a.find('my')
-1
index() 如果找不到返回异常
>>> a = 'My name is haha'
>>> a.index('name')
3
>>> a.index('my')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
lower() 转换所有大写字符转换成小写
>>> a = 'MY NAME IS HAHA'
>>> a.lower()
'my name is haha'
title() 把字符串标题化,所有字符开头是大写的;
>>> a = 'my name is haha'
>>> a.title()
'My Name Is Haha'
istitle() 判断是否是标题化的字符串;
>>> a = a.title()
>>> a
'My Name Is Haha'
>>> a.istitle()
True
lstrip() 截掉字符串左边的空格;
>>> a = ' my name is haha'
>>> a
' my name is haha'
>>> a.lstrip()
'my name is haha'
replace('old','new') 替换操作;
>>> a = a.lstrip()
>>> a
'my name is haha'
>>> a.replace('haha','hello')
'my name is hello'
rstrip() 截掉字符串右边的空格;
>>> a = 'my name is hah '
>>> a
'my name is hah '
>>> a.rstrip()
'my name is hah'
split() 以str做分割字符串;
>>> a = 'zhangsan lisi wangye'
>>> a.split()
['zhangsan', 'lisi', 'wangye']