Python的字符串操作函数
Python的字符串操作函数有很多,这里总结了其中比较常用的几个函数。
1. len()
该函数用于计算一个字符串的长度。示例:
string = "Hello world" print(len(string))
输出:11
2. split()
该函数用于将一个字符串根据指定字符分割成多个子字符串,并返回一个列表。示例:
string = "Hello world"
print(string.split(" "))
输出:['Hello', 'world']
3. join()
该函数将列表中的元素连接成一个字符串。示例:
string = ["Hello", "world"]
print(" ".join(string))
输出:Hello world
4. replace()
该函数用于替换字符串中的子字符串。示例:
string = "Hello world"
print(string.replace("world", "python"))
输出:Hello python
5. lower() 和 upper()
lower()函数用于将字符串中的所有字母转为小写,upper()函数用于将所有字母转为大写。示例:
string = "Hello world" print(string.lower()) print(string.upper())
输出:hello world HELLO WORLD
6. strip()
该函数用于去除字符串左右两边的空格。示例:
string = " Hello world " print(string.strip())
输出:Hello world
7. find() 和 index()
find()函数用于查找字符串中是否包含指定的子字符串,如果包含则返回子字符串在字符串中的位置,否则返回-1。index()函数也是用于查找字符串中是否包含指定的子字符串,但是如果不包含则会报错。示例:
string = "Hello world"
print(string.find("world"))
print(string.find("python"))
print(string.index("world"))
print(string.index("python"))
输出:6 -1 6 Traceback (most recent call last): ...
8. startswith() 和 endswith()
startswith()函数用于判断一个字符串是否以指定的子字符串开头,endswith()函数用于判断一个字符串是否以指定的子字符串结尾。示例:
string = "Hello world"
print(string.startswith("Hello"))
print(string.endswith("world"))
输出:True True
9. isdigit() 和 isalpha()
isdigit()函数用于判断一个字符串是否只包含数字字符,isalpha()函数用于判断一个字符串是否只包含字母字符。示例:
string1 = "123" string2 = "abc" print(string1.isdigit()) print(string2.isalpha())
输出:True True
10. format()
该函数用于将参数格式化成指定格式的字符串。示例:
name = "Alice"
age = 20
print("{} is {} years old".format(name, age))
输出:Alice is 20 years old
以上是Python字符串操作函数中比较常用的函数,希望能够对大家有所帮助。
