capitalize(self)
返回值:将字符串的第一个首字母变成大写,其他字母变小写
s = 'hello World'ss = s.capitalize()print(ss)
Hello world
casefold(self)
返回值:字符串内所有字符大写变小写。魔法范围比.lower()大。
s = 'Are you Ok ?'ss = s.casefold()print(ss)
are you ok ?
lower(self)
返回值:字符串内所有字符大写变小写。魔法范围比casefold()小
s = 'Are you Ok ?'ss = s.lower()print(ss)
are you ok ?
Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter ‘ß’ is equivalent to “ss”. Since it is already lowercase, lower() would do nothing to ‘ß’; casefold() converts it to “ss”.
expandtabs(tabsize
=
8
)
方法把字符串中的 tab 符号(‘\t’)转为空格,默认的空格数 tabsize 是 8,也可以指定其他数值。
下例中转换方式为,从左向右数5个字符,没有\t就继续数5个 例如 username\tpasswd….遇到ame\t的时候就换成2个空格再继续数(5-3)
s = 'username\tpasswd\temail\nzhuge\t123\tzhuge@sg.com\nzhuge\t123\tzhuge@sg.com\nzhuge\t123\tzhuge@sg.com\n'ss = s.expandtabs(5)print(ss)
username passwd emailzhuge 123 zhuge@sg.comzhuge 123 zhuge@sg.comzhuge 123 zhuge@sg.com
join(sequence)
方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
参数:sequence — 要连接的元素序列。str1.join(str2)用str1链接str2序列
s = 'hello'ss = '-'.join(s)print(ss)
h-e-l-l-o
split([sep[, num=maxsplit]])
通过指定分隔符(sep)对字符串进行切片,如果参数(num) 有指定值n,则仅切n次,num默认为最大限度切割。
s = 'i love you, i l o v e y o u'ss = s.split()sss = s.split(' ', 1)print(ss)print(sss)l = '1+2+3+4+5'll = l.split('+', 3)print(ll)
['i', 'love', 'you,', 'i', 'l', 'o', 'v', 'e', 'y', 'o', 'u']['i', 'love you, i l o v e y o u']['1', '2', '3', '4+5']
find(str,[beg=0,[end=len(string)]])
查找子串str在字符串的开始位置。
从下标为beg(默认为0)的位置开始找,直到索引为end(默认到结尾)处,如果找到,则返回此子串对应的索引,找不到就返回-1。
s = 'abcdefabc'ss = s.find('c')sss = s.find('c', 3)ssss = s.find('h')print(ss), print(sss), print(ssss)
28-1
strip([chars])
方法用于移除字符串头尾指定的字符(chars)(默认为空格)。
扩展:lstrip() rstrip()可用于删除左边/右边的指定字符。
s = '-----hello world--'ss = s.strip('-')sss = s.lstrip('-')print(ss), print(sss
hello worldhello world--
upper()
返回值:将字符串中的小写字母转为大写字母。
s = 'hello'ss = s.upper()print(ss)
HELLO
lower()
返回值:与upper()相反地,将字符串中所有大写字符转换为小写。
s = 'HELLO'ss = s.lower()print(ss)
hello
replace(old, new[, max])
方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
s = 'abcdabcdabcd'ss = s.replace('abc', 'e')sss = s.replace('abc', 'e', 2)print(ss), print(sss)
edededededabcd
isdigit()
方法检测字符串是否只由数字组成,如果字符串只包含数字,罗马数字)则返回 True 否则返回 False.
# isdigit()# True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字# False: 汉字数字# Error: 无## isdecimal()# True: Unicode数字,,全角数字(双字节)# False: 罗马数字,汉字数字# Error: byte数字(单字节)## isnumeric()# True: Unicode数字,全角数字(双字节),罗马数字,汉字数字# False: 无# Error: byte数字(单字节)
isalpha()
字符串至少有一个字符并且所有字符都是字母则返回 True,否则返回 False