欢迎访问宙启技术站
智能推送

Python中常用字符串处理函数介绍及示例代码

发布时间:2023-08-11 22:48:23

Python中有许多常用的字符串处理函数,这些函数可以对字符串进行各种操作,如拼接、分割、查找、替换等。本文将介绍一些常用的字符串处理函数,并给出相应的示例代码。

1. len(string): 返回字符串的长度

示例代码:

string = "Hello, world!"
length = len(string)
print(length)  # 输出 13

2. string.lower() / string.upper(): 将字符串中的字母全部转换为小写/大写

示例代码:

string = "Hello, WORLD!"
lowercase = string.lower()
uppercase = string.upper()
print(lowercase)  # 输出 "hello, world!"
print(uppercase)  # 输出 "HELLO, WORLD!"

3. string.strip(): 去除字符串两端的空格

示例代码:

string = "   hello, world!   "
stripped_string = string.strip()
print(stripped_string)  # 输出 "hello, world!"

4. string.split(separator): 将字符串按separator分割成一个列表

示例代码:

string = "apple,banana,orange"
fruits = string.split(",")
print(fruits)  # 输出 ["apple", "banana", "orange"]

5. string.join(iterable): 把可迭代对象中的字符串连接起来,以string作为分隔符

示例代码:

fruits = ["apple", "banana", "orange"]
string = ",".join(fruits)
print(string)  # 输出 "apple,banana,orange"

6. string.find(substring): 查找并返回字符串中 次出现substring的索引,若没有找到则返回-1

示例代码:

string = "Hello, world!"
index = string.find("world")
print(index)  # 输出 7

7. string.replace(old, new): 将字符串中所有的old替换为new

示例代码:

string = "Hello, world!"
new_string = string.replace("world", "Python")
print(new_string)  # 输出 "Hello, Python!"

8. string.startswith(str): 判断字符串是否以str开头

示例代码:

string = "Hello, world!"
starts_with_hello = string.startswith("Hello")
print(starts_with_hello)  # 输出 True

9. string.endswith(str): 判断字符串是否以str结尾

示例代码:

string = "Hello, world!"
ends_with_exclamation = string.endswith("!")
print(ends_with_exclamation)  # 输出 True

10. string.isdigit(): 判断字符串是否只包含数字字符

示例代码:

string = "123"
is_digit = string.isdigit()
print(is_digit)  # 输出 True

这些是Python中常用的字符串处理函数和相应的示例代码。掌握这些函数的用法,可以更加高效地处理和操作字符串。