字符串操作函数-Python中的字符串操作函数合集
Python 是一门高级编程语言,它提供了许多操作字符串的函数。这些函数涵盖了Python中字符串操作的多个方面,包括字符串长度、字母大小写转换、字符串切割、字符串拼接等等。本文将介绍Python中常用的字符串操作函数。
1. 字符串长度
len()函数可以用来获取字符串的长度,它不仅适用于普通字符串,还适用于Unicode字符串。
str = "Hello World!" print(len(str))
输出结果为:12。
2. 字符串大小写转换
Python中,可以使用str.upper()和str.lower()函数来实现将字符串转换为大写或小写。
str = "Hello World!" print(str.upper()) str = "Hello World!" print(str.lower())
输出结果为:
HELLO WORLD! hello world!
3. 字符串切割
Python中,可以使用str.split()函数将字符串按指定的字符串分隔符分割成列表。
str = "Hello,World!"
result = str.split(",")
print(result)
输出结果为:
['Hello', 'World!']
4. 字符串拼接
Python中,可以使用"+"或者字符串的join()函数来实现字符串的拼接。
str1 = "Hello" str2 = "World!" result = str1 + str2 print(result) str1 = "Hello" str2 = "World!" separator = "," result = separator.join([str1, str2]) print(result)
输出结果为:
HelloWorld! Hello,World!
5. 字符串替换
Python中,可以使用str.replace()函数来实现字符串中的字符替换。
str = "Hello World!"
result = str.replace("o", "0")
print(result)
输出结果为:
Hell0 W0rld!
6. 去除字符串前后的空格
Python中,可以使用str.strip()函数来实现去除字符串前后的空格。
str = " Hello World! " result = str.strip() print(result)
输出结果为:
Hello World!
7. 字符串查找
Python中,可以使用str.find()函数来实现在字符串中查找子串的位置。
str = "Hello World!"
result = str.find("World")
print(result)
输出结果为:6,即子串"World"的起始位置。
8. 字符串计数
Python中,可以使用str.count()函数来计算字符串中某个字符或子串出现的次数。
str = "Hello World!"
result = str.count("o")
print(result)
输出结果为:2,即字符"o"在字符串中出现的次数。
9. 字符串格式化
Python中,可以使用格式化字符串方法来进行字符串格式化。
str = "Hello {}!"
result = str.format("World")
print(result)
输出结果为:
Hello World!
总之,Python中的字符串操作函数丰富多样,从字符串长度、大小写转换、字符串切割、字符串拼接、字符串替换、去除字符串前后的空格、字符串查找、字符串计数以及字符串格式化等方面,都提供了相应的函数。简单掌握这些函数,将极大地提高Python程序开发的效率。
