Python中常见的字符串操作函数(例如split、join、replace等)
Python中字符串操作函数十分丰富,这些函数帮助我们对字符串进行各种处理。下面我们来介绍和说明几个常用的字符串函数。
1. split
split函数用于将一个字符串按照指定的分隔符进行拆分,返回一个由拆分后的子字符串组成的列表。例如:
str = "hello world"
list = str.split(" ")
print(list)
这段代码会将字符串"hello world"按照空格进行拆分,返回一个列表['hello', 'world']。
2. join
join函数用于将列表或者元组中的字符串按照指定的分隔符进行连接,返回一个新的字符串。例如:
list = ['hello', 'world'] str = " ".join(list) print(str)
这段代码会将列表['hello','world']中的字符串按照空格进行拼接成一个新的字符串"hello world"。
3. replace
replace函数用于将一个字符串中的指定子字符串替换成另一个字符串,返回一个新的字符串。例如:
str = "hello world"
new_str = str.replace("hello", "hi")
print(new_str)
这段代码会将字符串"hello world"中的子字符串"hello"替换成"hi",返回一个新的字符串"hi world"。
4. strip
strip函数用于去除一个字符串中的首尾指定字符,默认去除空格。例如:
str = " hello world " new_str = str.strip() print(new_str)
这段代码会将字符串" hello world "的首尾空格去除,返回一个新的字符串"hello world"。
5. find
find函数用于在一个字符串中查找指定子字符串的位置,返回找到的 个位置的索引,如果未找到则返回-1。例如:
str = "hello world"
index = str.find("world")
print(index)
这段代码会在字符串"hello world"中查找子字符串"world"的位置,返回值为6。
6. replace
replace函数用于将一个字符串中的指定子字符串替换成另一个字符串,返回一个新的字符串。例如:
str = "hello world"
new_str = str.replace("hello", "hi")
print(new_str)
这段代码会将字符串"hello world"中的子字符串"hello"替换成"hi",返回一个新的字符串"hi world"。
7. upper
upper函数用于将一个字符串中的所有字符转换成大写字母,返回一个新的字符串。例如:
str = "hello world" new_str = str.upper() print(new_str)
这段代码会将字符串"hello world"全部转换成大写字母,返回一个新的字符串"HELLO WORLD"。
8. lower
lower函数用于将一个字符串中的所有字符转换成小写字母,返回一个新的字符串。例如:
str = "HELLO WORLD" new_str = str.lower() print(new_str)
这段代码会将字符串"HELLO WORLD"全部转换成小写字母,返回一个新的字符串"hello world"。
这些函数只是Python中常见的字符串操作函数中的一部分,有时候我们还可以用正则表达式等技巧来进行字符串的处理。不过掌握这些常用的字符串操作函数已经足够我们进行大部分的字符串处理。
