Python中关于字符串的处理函数
Python中有许多关于字符串的处理函数,以下介绍其中一些常用的函数。
1. len()
len()函数用于返回字符串的长度,即字符串中字符的个数。
示例:
s = "hello" print(len(s))
输出结果为:5
2. str()
str()函数用于将其他类型的数据转换为字符串类型。常用于将数字转换为字符串。
示例:
num = 123 print(str(num) + " is a number")
输出结果为:123 is a number
3. upper()
upper()函数用于将字符串中的小写字母转换为大写字母。
示例:
s = "hello" print(s.upper())
输出结果为:HELLO
4. lower()
lower()函数用于将字符串中的大写字母转换为小写字母。
示例:
s = "HELLO" print(s.lower())
输出结果为:hello
5. strip()
strip()函数用于去掉字符串开头和结尾的空格。
示例:
s = " hello " print(s.strip())
输出结果为:hello
6. replace()
replace()函数用于替换字符串中的某个字符或字符串。
示例:
s = "hello world"
print(s.replace("world", "python"))
输出结果为:hello python
7. split()
split()函数用于将一个字符串按照指定的分隔符分割成多个子字符串,并将这些子字符串放在一个列表中返回。
示例:
s = "hello,world,python"
print(s.split(","))
输出结果为:['hello', 'world', 'python']
8. join()
join()函数用于将一个字符串列表连接成一个字符串。
示例:
s = ["hello", "world", "python"]
print("-".join(s))
输出结果为:hello-world-python
9. format()
format()函数用于格式化字符串。
示例:
name = "Tom"
age = 18
print("My name is {}, and I am {} years old".format(name, age))
输出结果为:My name is Tom, and I am 18 years old
10. find()
find()函数用于查找指定字符串在另一个字符串中 次出现的位置,并返回该位置的索引值。如果未找到指定字符串,则返回-1。
示例:
s = "hello world"
print(s.find("world"))
输出结果为:6
11. count()
count()函数用于计算指定字符在字符串中出现的次数。
示例:
s = "hello world"
print(s.count("o"))
输出结果为:2
总结:
以上函数是Python中常用的字符串处理函数,了解了这些函数的基本用法,可以使我们更加便捷地操作字符串。
