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

10必备Python函数:从字符串到列表的转换

发布时间:2023-06-20 02:59:20

Python是一种非常流行的编程语言,它有丰富的函数库,可以实现各种各样的操作。在这里我们将介绍10个必备的Python函数,用于从字符串到列表的转换。

1. split

split是Python中最为常用的字符串分割函数,它可以将一个字符串以特定的字符为分隔符进行分割,并返回一个列表。例如:

str = "Hello world, welcome to Python"
list = str.split(" ")
print(list)

输出结果为:

['Hello', 'world,', 'welcome', 'to', 'Python']

2. join

join是Python中用于连接字符串的函数。它将一个列表字符串连接成一个单一的字符串。例如:

list = ['Hello', 'world,', 'welcome', 'to', 'Python']
str = " ".join(list)
print(str)

输出结果为:

Hello world, welcome to Python

3. strip

strip可以用来去掉字符串开头和结尾的空格和换行符。例如:

str = "    Hello world!    
"
str = str.strip()
print(str)

输出结果为:

Hello world!

4. replace

replace可以用于将指定字符串替换成另一个字符串。例如:

str = "Hello World"
str = str.replace("World", "Python")
print(str)

输出结果为:

Hello Python

5. find

find函数可以用来查找字符串是否包含指定的子字符串,如果包含则返回其在字符串中的位置,不包含则返回-1。例如:

str = "Hello World"
print(str.find("World"))

输出结果为:

6

6. startswith

startswith函数可以用来判断一个字符串是否以指定的字符串开头。例如:

str = "Hello World"
print(str.startswith("Hello"))

输出结果为:

True

7. endswith

endswith函数可以用来判断一个字符串是否以指定的字符串结尾。例如:

str = "Hello World"
print(str.endswith("World"))

输出结果为:

True

8. count

count函数可以用来计算一个字符串中指定字符出现的次数。例如:

str = "Hello World"
print(str.count("l"))

输出结果为:

3

9. upper

upper函数可以将字符串中所有的小写字母转换成大写字母。例如:

str = "hello world"
print(str.upper())

输出结果为:

HELLO WORLD

10. lower

lower函数可以将字符串中所有的大写字母转换成小写字母。例如:

str = "HELLO WORLD"
print(str.lower())

输出结果为:

hello world

这些函数都是在Python编程中必不可少的函数,对于从字符串到列表的转换尤为重要。使用这些函数,可以使程序更加高效、简洁和易于维护。