1. capitalize()
将字符串变为首字母大写的格式。
示例:
str = 'my name is jack.'
print(str.capitalize())
输出:
My name is jack.
2. casefold()
将字符串全部转化为小写格式。
示例:
text = 'Success Can Be Difficult To Measure'
x = text.casefold()
print(x)
输出:
success can be difficult to measure
3. center()
将字符串置中,并在开头和结尾填充特定的字符。
用法:
str.center(width, fillChar)
- witdth - 转化后的总长度
- fillChar - 填充的字符,默认是’ ’
示例:
text = '今日多云转晴'
x = text.center(14)
print(x)
x2 = text.center(14, '|')
print(x2)
输出:
今日多云转晴
||||今日多云转晴||||
4. count()
返回字符串中某个子串出现的次数。
用法:
str.count(substring, start, end)
- subsring - 需要统计的子串
- start - 开始查找的下标值,默认为0
- end - 结束查找的下标值,默认查找到最后一个字符
示例:
text = 'python is an amazing laguage, I love python'
res = text.count('python')
print(res)
输出:
2
5. encode()
将字符编码为需要的格式。
用法:
string.encode(encoding='UTF-8',errors='strict')
- encoding - 编码类型,默认’UTF-8’
- errors
- ‘strict’ - (默认) 失败时引发异常
- ‘ignore’ - 忽略不可编码的字符
- ‘replace’ - 遇到不可编码字符时,将其替换为’?’
- ‘xmlcharrefreplace’ - 用 xml 字符替换字符
- ‘namereplace’ - 用解释字符的文本替换字符
- backslashreplace’ - 使用反斜杠代替无法编码的字符
示例:
s = "Hello Python"
s1 = s.encode("ascii", "replace")
print(s1)
输出:
b’Hello Python’
6. endswith()
判断字符串是否由某个子串结尾。
用法:
str.endsWith(suffix, start, end)
- suffix - 需要判断的后缀
- start - 判断的起始位置
- end - 判断的结尾位置
示例:
files = ['car.jpg', 'plane.jpg', 'picture']
img = [file for file in files if file.endswith('.jpg')]
print(img)
输出:
[‘car.jpg’, ‘plane.jpg’]
7. find()
返回某个子串首次出现的下标值,若不存在,返回-1
用法:
str.find(substr, start, end)
示例:
sentence = 'Good Morning, Hello! Hello? How are you?'
# 1 first occurrence of 'Hello' (Case Sensitive)
result = sentence.find('Hello')
print("#1:",result)
# 2 returns -1 if substring not found
result = sentence.find('Bye')
print("#2:", result)
输出:
#1: 14
#2: -1