capitalize()
将首字母大写,其他字母小写(只对首个字符是字母有效)
# coding:utf-8
name = 'bai ze'
info = 'hello 白泽'
_info = '白泽 hello'
number_str = '1234'
print(name.capitalize())
print(info.capitalize())
print(_info.capitalize())
print(number_str.capitalize())
运行结果:
Bai ze
Hello 白泽
白泽 hello
1234
casefold()和lower()
使字符串中所有字母小写
区别:lower()只能操作英文字母 casefold()可以操作更多语种(例如:德语)
# coding:utf-8
name = 'BAI ZE!'
print(name.lower())
print(name.casefold())
运行结果:
bai ze!
bai ze!
upper()
使字符串中所有字母大写
# coding:utf-8
name = 'bai ze!'
print(name.upper())
运行结果:
BAI ZE!
swapcase()
将字符串中的大小写字母进行转换(小写变大写,大写变小写)
# coding:utf-8
name = 'Bai Ze'
print(name.swapcase())
运行结果:
bAI zE
zfill(length)
为字符串定义长度,不满足的部分用0替代,若定义的长度小于或等于当前字符串长度,则不会发生变化
# coding:utf-8
name = 'Bai Ze'
new_name_10 = name.zfill(10)
new_name_1 = name.zfill(1)
print(new_name_1)
print(new_name_10)
运行结果:
Bai Ze
0000Bai Ze
count(item)
返回当前字符串中某个成员的个数
# coding:utf-8
info = 'Bai Ze Hahahaha~'
info_count_a = info.count('a')
info_count_b = info.count('b')
print(info_count_a)
print(info_count_b)
运行结果:
5
0
startswith(item)和endswith(item)
判断字符串开头和结尾是否为item,返回布尔值
# coding:utf-8
info = 'Bai ze shang shen'
print(info.startswith('Bai'))
print(info.startswith('ze'))
print(info.endswith('shen'))
print(info.endswith('shang'))
运行结果:
True
False
True
False
find(item)和index(item)
返回字符串中查询元素从左到右第一次出现的位置(位置从0开始)
区别:
find找不到元素会返回-1
index找不到元素会直接导致程序报错
# coding:utf-8
info = 'Bai ze shang shen'
print(info.find('a'))
print(info.find('ok'))
print(info.index('a'))
print(info.index('ok'))
运行结果:
1
-1
1
ValueError: substring not found
strip(item)
消除字符串左右两边的指定元素,item不填则默认消除左右两边的空格
lstrip(item)
消除字符串开头的指定元素,item不填则默认消除开头的空格
rstrip(item)
消除字符串结尾的指定元素,item不填则默认消除结尾的空格
# coding:utf-8
info = ' Bai ze shang shen '
print(info + '.') # 加.方便显示空格
print(info.strip() + '.')
print(info.lstrip() + '.')
print(info.rstrip() + '.')
print(info.strip('n ') + '.')
运行结果:
Bai ze shang shen .
Bai ze shang shen.
Bai ze shang shen .
Bai ze shang shen.
Bai ze shang she.
replace(old,new,[max])
使用元素new替换元素old,max可选,代表替换几个,不填默认全部替换
# coding:utf-8
info = 'abababab'
print(info.replace('a','c')) # 将所有的a替换成c
print(info.replace('a','c',2)) # 将前两个a替换成c
运行结果:
cbcbcbcb
cbcbabab
isspace()
判断字符串是否仅由空格组成
istitle()
判断字符串是否是一个标题类型(每个单词只有首字母大写就是标题)
isupper()
判断字符串中字母是否全为大写
islower()
判断字符串中字母是否全为小写
# coding:utf-8
str_space = ' '
str_title = 'Bai Ze'
str_lower = 'bai ze'
str_upper = 'BAI ZE'
print(str_space.isspace(),str_title.isspace())
print(str_title.istitle(),str_lower.istitle(),str_upper.istitle())
print(str_lower.islower(),str_upper.islower())
print(str_upper.isupper(),str_lower.isupper())
运行结果:
True False
True False False
True False
True False
index(item) find(item)
获取item在字符串上第一次出现的位置
find函数找不到元素会返回-1
index函数找不到元素会直接报错
# coding:utf-8
info = 'Bai Ze Shang Shen'
print(info.index('e'))
print(info.find('S'))
print(info.find('OK'))
运行结果:
5
7
-1