Python字符串相关函数及实用例子
发布时间:2023-09-26 23:25:55
Python是一种非常流行的编程语言,它具有丰富的字符串操作函数。本文将介绍Python中常用的字符串函数,并提供一些实用的例子。
1. len()函数:返回字符串的长度。
例子:
string = "Hello, world!" print(len(string)) # 输出:13
2. str()函数:将其他类型的数据转换为字符串。
例子:
number = 123 string = str(number) print(string) # 输出:"123"
3. find()函数:查找字符串中包含的子字符串,并返回其 次出现的索引。如果未找到,则返回-1。
例子:
string = "Hello, world!"
index = string.find("world")
print(index) # 输出:7
4. replace()函数:替换字符串中的指定子字符串。
例子:
string = "Hello, world!"
new_string = string.replace("world", "Python")
print(new_string) # 输出:"Hello, Python!"
5. split()函数:将字符串按照指定的分隔符分割成一个列表。
例子:
string = "Hello, world!"
splitted = string.split(",")
print(splitted) # 输出:['Hello', ' world!']
6. join()函数:将一个列表中的字符串连接成一个字符串,使用指定的分隔符。
例子:
splitted = ['Hello', ' world!'] joined = "-".join(splitted) print(joined) # 输出:"Hello- world!"
7. isalpha()函数:检查字符串是否只包含字母字符。
例子:
string = "Hello" print(string.isalpha()) # 输出:True
8. isdigit()函数:检查字符串是否只包含数字字符。
例子:
string = "123" print(string.isdigit()) # 输出:True
9. upper()函数:将字符串中的所有字母字符转换为大写。
例子:
string = "Hello, world!" print(string.upper()) # 输出:"HELLO, WORLD!"
10. lower()函数:将字符串中的所有字母字符转换为小写。
例子:
string = "Hello, world!" print(string.lower()) # 输出:"hello, world!"
11. startswith()函数:检查字符串是否以指定的子字符串开头。
例子:
string = "Hello, world!"
print(string.startswith("Hello")) # 输出:True
12. endswith()函数:检查字符串是否以指定的子字符串结尾。
例子:
string = "Hello, world!"
print(string.endswith("world!")) # 输出:True
13. strip()函数:去除字符串首尾的空白字符。
例子:
string = " Hello, world! " print(string.strip()) # 输出:"Hello, world!"
14. format()函数:格式化字符串,将变量插入到字符串中。
例子:
name = "Alice"
age = 20
message = "My name is {} and I am {} years old.".format(name, age)
print(message) # 输出:"My name is Alice and I am 20 years old."
这些函数只是Python中字符串函数的一小部分,但它们是最常见和实用的函数之一。掌握了这些函数,您可以更好地处理和操作字符串数据。
