Python中的字符串函数及其示例代码
1. len() 函数
len() 函数用于获取字符串的长度。
示例代码:
str = "Hello World!"
print("长度为:", len(str))
输出结果:
长度为: 12
2. capitalize() 函数
将字符串的第一个字符转换为大写字母,其余字符全部转换为小写字母。
示例代码:
str = "hello world!"
print("首字母大写:", str.capitalize())
输出结果:
首字母大写: Hello world!
3. lower() 函数
将字符串中的所有大写字母转换为小写字母。
示例代码:
str = "Hello World!"
print("转换为小写:", str.lower())
输出结果:
转换为小写: hello world!
4. upper() 函数
将字符串中的所有小写字母转换为大写字母。
示例代码:
str = "Hello World!"
print("转换为大写:", str.upper())
输出结果:
转换为大写: HELLO WORLD!
5. swapcase() 函数
将字符串中的大写字母转换为小写字母,小写字母转换为大写字母。
示例代码:
str = "Hello World!"
print("大小写互换:", str.swapcase())
输出结果:
大小写互换: hELLO wORLD!
6. title() 函数
将字符串中每个单词的第一个字母转换为大写字母,其余字母转换为小写字母。
示例代码:
str = "hello world!"
print("每个单词首字母大写:", str.title())
输出结果:
每个单词首字母大写: Hello World!
7. center() 函数
将字符串居中,并用指定字符填充字符串的左右两侧。
示例代码:
str = "hello"
print(str.center(20,'*'))
输出结果:
*******hello*******
8. count() 函数
计算字符串中指定子串出现的次数。
示例代码:
str = "hello world!"
print("o出现的次数:", str.count('o'))
输出结果:
o出现的次数: 2
9. endswith() 函数
判断字符串是否以指定的后缀结尾。
示例代码:
str = "hello world!"
print(str.endswith('!'))
输出结果:
True
10. startswith() 函数
判断字符串是否以指定的前缀开头。
示例代码:
str = "hello world!"
print(str.startswith('hello'))
输出结果:
True
11. find() 函数
在字符串中查找指定子串,返回子串在字符串中首次出现的位置。
示例代码:
str = "hello world!"
print(str.find('lo'))
输出结果:
3
12. replace() 函数
将字符串中指定的子串替换为另一个子串。
示例代码:
str = "hello world!"
print(str.replace('o', '*'))
输出结果:
hell* w*rld!
13. split() 函数
将字符串按指定分隔符分割成一个字符串列表。
示例代码:
str = "hello,world!"
print(str.split(','))
输出结果:
['hello', 'world!']
14. join() 函数
将多个字符串连接成一个字符串。
示例代码:
lst = ['hello', 'world!']
print(','.join(lst))
输出结果:
hello,world!
15. strip() 函数
去除字符串首尾指定的字符。
示例代码:
str = " hello "
print(str.strip())
输出结果:
hello
以上就是Python中常用的字符串函数及其示例代码。这些函数可以帮助我们快速操作字符串,实现我们想要的功能。
