Python字符串处理函数:使用常见字符串处理函数进行字符串操作
发布时间:2023-07-02 05:11:12
Python提供了很多常见的字符串处理函数,可以方便地进行字符串操作。下面是一些常见的字符串处理函数及其用法:
1. len():返回字符串的长度。
s = "Hello World" print(len(s)) # 输出 11
2. str.upper()和str.lower():将字符串全部转换为大写或小写。
s = "Hello World" print(s.upper()) # 输出 HELLO WORLD print(s.lower()) # 输出 hello world
3. str.title()和str.capitalize():将字符串中的每个单词的首字母大写或只将 个单词的首字母大写。
s = "hello world" print(s.title()) # 输出 Hello World print(s.capitalize()) # 输出 Hello world
4. str.startswith(sub)和str.endswith(sub):判断字符串是否以指定的子字符串开头或结尾,并返回布尔值。
s = "Hello World"
print(s.startswith("Hello")) # 输出 True
print(s.endswith("World")) # 输出 True
5. str.find(sub)和str.index(sub):在字符串中查找指定的子字符串并返回 次出现的索引位置。如果不存在,则返回-1或抛出异常。
s = "Hello World"
print(s.find("World")) # 输出 6
print(s.find("Python")) # 输出 -1
print(s.index("World")) # 输出 6
# print(s.index("Python")) # 抛出 ValueError 异常
6. str.count(sub):统计字符串中指定子字符串的出现次数。
s = "Hello World"
print(s.count("o")) # 输出 2
7. str.replace(old, new):将字符串中的旧子字符串替换为新的子字符串。
s = "Hello World"
print(s.replace("World", "Python")) # 输出 Hello Python
8. str.strip()、str.lstrip()和str.rstrip():去除字符串两端或左端或右端的指定字符(默认为空格字符)。
s = " Hello World " print(s.strip()) # 输出 "Hello World" print(s.lstrip()) # 输出 "Hello World " print(s.rstrip()) # 输出 " Hello World"
9. str.split()和str.join():将字符串拆分成列表或通过指定字符连接列表中的元素。
s = "Hello World"
print(s.split()) # 输出 ['Hello', 'World']
words = ['Hello', 'World']
print(' '.join(words)) # 输出 "Hello World"
10. str.isdigit()、str.isalpha()、str.isalnum()、str.islower()、str.isupper():判断字符串是否只包含数字、字母、数字和字母的组合、全部小写字母、全部大写字母,并返回布尔值。
s1 = "12345" s2 = "Hello" s3 = "123Hello" s4 = "hello" s5 = "WORLD" print(s1.isdigit()) # 输出 True print(s2.isalpha()) # 输出 True print(s3.isalnum()) # 输出 True print(s4.islower()) # 输出 True print(s5.isupper()) # 输出 True
以上是一些常见的字符串处理函数及其用法,利用这些函数可以方便地进行字符串操作。当然,Python还提供了更多的字符串处理函数,具体可以查看Python官方文档。
