1、zfill(width)
若string字符串长度小于width,则会将string字符串左侧补字符‘0’扩充至width长度
string = "hello"
print(string.zfill(8))
结果为:
000hello
2、capitalize()
将string字符串的首字母变为大写
string = "hello world"
print(string.capitalize())
结果为:
Hello world
3、swapcase()
将string字符串的字符大小写相互转换
string = "Hello World"
print(string.swapcase())
结果为:
hELLO wORLD
4、title()
将string字符串的以空格分隔的每个单词的首字母变为大写
string = "hello world"
print(string.title())
结果为:
Hello World
5、upper()
将string字符串的全部字符变为大写
string = "hello world"
print(string.upper())
结果为:
HELLO WORLD
6、lower()
将string字符串的全部字符变为小写
string = "HELLO WORLD"
print(string.lower())
结果为:
hello world
7、strip()
删除string字符串的左右空格
string = " hello world "
print(string.strip())
结果为:
hello world
8、rstrip()
删除string字符串的右边空格
string = " hello world "
print(string.rstrip())
结果为:
hello world
9、lstrip()
删除string字符串的左边空格
string = " hello world "
print(string.lstrip())
结果为:
hello world
10、startswith(str)
判断string字符串是否以给定字符串str开头,返回值为布尔类型
string = "hello world"
print(string.startswith("he"))
print(string.startswith("e"))
结果为:
True
False
11、endswith(str)
判断string字符串是否以给定字符串str结尾,返回值为布尔类型
string = "hello world"
print(string.endswith("ld"))
print(string.endswith("l"))
结果为:
True
False
12、splitlines()
将string字符串以换行符分割,返回一个列表
string = "hello\nworld"
print(string.splitlines())
结果为:
['hello', 'world']
13、split(str)
将string字符串以给定字符str分割,返回一个列表
string = "hello,world"
print(string.split(","))
结果为:
['hello', 'world']
14、rsplit(str)
将string字符串以给定字符str分割,从右边开始,返回一个列表
string = "hello world"
print(string.split("o"))
结果为:
['hell', ' w', 'rld']
15、rpartition(str)
将string字符串以给定字符str分割,从右边数只切割一次,返回一个元组
string = "hello world"
print(string.rpartition("o"))
结果为:
('hello w', 'o', 'rld')
16、ljust(width,str=" ")
若string字符串总长度小于所填参数width,则在字符串的右侧填充给定字符str,默认为空格
string = "hello"
print(string.ljust(8,"0"))
结果为:
hello000
17、rjust(width,str=" ")
若string字符串总长度小于所填参数width,则在字符串的左侧填充给定字符str,默认为空格
string = "hello"
print(string.rjust(8, "0"))
结果为:
000hello
18、rindex(str)
返回string字符串中右数第一个匹配的字符串str的索引,没有找到则报错
string = "hello world"
print(string.rindex("o"))
print(string.rindex("s"))
结果为:
7
ValueError: substring not found
19、rfind(str)
返回string字符串侧数第一个匹配的字符串str的索引,没有找到则返回-1
string = "hello world"
print(string.rfind("o"))
print(string.rfind("s"))
结果为:
7
-1
20、replace(oldstr, newstr)
将字符串string中的oldstr替换成newstr
string = "hello world"
print(string.replace("o", "s"))
结果为:
hells wsrld
21、partition(str)
将字符串string以给定字符串str分割,返回以给定字符串str分割的元组,(分隔符之前的字符串, 分隔符本身, 分隔符之后的字符串),若找不到分割符则返回字符串本身和两个空字符串
string = "hello,world"
print(string.partition("o,"))
print(string.partition("sw"))
结果为:
('hell', 'o,', 'world')
('hello,world', '', '')