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

Python字符串处理中常用的函数及其用法

发布时间:2023-06-19 07:08:48

在Python编程中,字符串是一个最常用的对象。既然字符串如此重要,那么我们就有必要学习一些最常用的字符串处理函数,以便处理文本、解析数据、格式化输出等方面的任务。本文将介绍一些 Python 字符串处理中比较实用的字符串函数,希望能对初学者有所帮助。

1. len(string)

这个函数返回字符串的长度,例如:

text = "hello world!"

length = len(text)

print(length) 

#输出结果:12 

2. string.upper() 和 string.lower()

这两个函数可以将字符串分别转换成全大写和全小写,例如:

text = "Hello World!"

print(text.upper()) 

# 输出结果:HELLO WORLD! 

text = "Hello World!"

print(text.lower()) 

# 输出结果:hello world! 

3. string.count(str)

计算字符串中给定子字符串出现的次数,例如:

text = "Python is a popular programming language."

print(text.count("p")) 

# 输出结果:2 

4. string.find(str)

返回子字符串在字符串中首次出现的位置,如果不存在则返回 -1,例如:

text = "Python is a popular programming language."

print(text.find("p")) 

# 输出结果:10 

print(text.find("Python")) 

# 输出结果:0 

5. string.replace(old_str, new_str)

将字符串中的子字符串 old_str 替换成 new_str,例如:

text = "Python is a popular programming language."

new_text = text.replace("Python", "Java")

print(new_text) 

# 输出结果:Java is a popular programming language. 

6. string.startswith(str)

判断字符串是否以给定子字符串开头,例如:

text = "Python is a popular programming language."

print(text.startswith("Python")) 

# 输出结果:True 

print(text.startswith("Java")) 

# 输出结果:False 

7. string.endswith(str)

判断字符串是否以给定子字符串结尾,例如:

text = "Python is a popular programming language."

print(text.endswith("language.")) 

# 输出结果:True 

print(text.endswith("Python")) 

# 输出结果:False 

8. string.strip()

去掉字符串两端的空白符号,例如:

text = "  Python  "

new_text = text.strip()

print(new_text) 

# 输出结果:Python 

9. string.split(separator)

将字符串按照给定的分隔符分割成多个子字符串,返回一个列表,例如:

text = "Python is a popular programming language."

words = text.split(" ")

print(words) 

# 输出结果:["Python", "is", "a", "popular", "programming", "language."] 

10. "分隔符".join(list)

与 split() 函数相反,这个函数将列表中的元素按照给定的分隔符链接起来,例如:

words = ["Python", "is", "a", "popular", "programming", "language."]

text = " ".join(words)

print(text) 

# 输出结果:Python is a popular programming language. 

11. string.format()

将变量插入到字符串中,并实现字符串的格式化输出。这个函数是比较复杂的,这里只介绍一些最为常用的用法。

(1)使用普通占位符 {} ,例如:

name = "Tom"

age = 20

text = "My name is {} and I'm {} years old.".format(name, age)

print(text) 

# 输出结果:My name is Tom and I'm 20 years old. 

(2)使用索引号指定占位符的位置,例如:

name = "Tom"

age = 20

text = "My name is {0} and I'm {1} years old. {0} again".format(name, age)

print(text) 

# 输出结果:My name is Tom and I'm 20 years old. Tom again 

(3)使用参数名指定占位符的值,例如:

name = "Tom"

age = 20

text = "My name is {n} and I'm {a} years old.".format(n=name, a=age)

print(text) 

# 输出结果:My name is Tom and I'm 20 years old. 

除了上面的常用字符串处理函数外,Python 中还有很多其他的字符串处理函数,多数是基于正则表达式的。对于初学者来说,上面介绍的这些函数已经足够应付日常的字符串处理任务,实践中也会逐渐学会其他函数。