Python中使用的10个常见字符串函数
发布时间:2023-07-01 14:30:16
1. len() - 返回字符串的长度。
2. str() - 将其他数据类型转换为字符串。
3. upper() - 将字符串转换为大写字母。
4. lower() - 将字符串转换为小写字母。
5. find() - 查找字符串中某个子字符串的位置。
6. replace() - 替换字符串中的某个子字符串。
7. split() - 将字符串按照指定的分隔符分割成多个子字符串。
8. join() - 将多个字符串合并为一个字符串。
9. isdigit() - 检查字符串是否只包含数字。
10. strip() - 去除字符串两端的空格或指定的字符。
下面是这些字符串函数的具体用法和示例:
1. len() - 返回字符串的长度。
string = "Hello world" length = len(string) print(length) # 输出: 11
2. str() - 将其他数据类型转换为字符串。
number = 123 string = str(number) print(string) # 输出: "123"
3. upper() - 将字符串转换为大写字母。
string = "hello" string_upper = string.upper() print(string_upper) # 输出: "HELLO"
4. lower() - 将字符串转换为小写字母。
string = "WORLD" string_lower = string.lower() print(string_lower) # 输出: "world"
5. find() - 查找字符串中某个子字符串的位置。
string = "Hello world"
index = string.find("world")
print(index) # 输出: 6
6. replace() - 替换字符串中的某个子字符串。
string = "Hello world"
new_string = string.replace("world", "Python")
print(new_string) # 输出: "Hello Python"
7. split() - 将字符串按照指定的分隔符分割成多个子字符串。
string = "Hello,Python,World"
strings = string.split(",")
print(strings) # 输出: ["Hello", "Python", "World"]
8. join() - 将多个字符串合并为一个字符串。
strings = ["Hello", "Python", "World"] new_string = "-".join(strings) print(new_string) # 输出: "Hello-Python-World"
9. isdigit() - 检查字符串是否只包含数字。
string = "123" is_digit = string.isdigit() print(is_digit) # 输出: True string = "123.45" is_digit = string.isdigit() print(is_digit) # 输出: False
10. strip() - 去除字符串两端的空格或指定的字符。
string = " Hello "
new_string = string.strip()
print(new_string) # 输出: "Hello"
string = "---Hello---"
new_string = string.strip("-")
print(new_string) # 输出: "Hello"
