Python 将一个字符串分割成多个子串
在 Python 中,可以使用 split() 方法将一个字符串分割成多个子串。split() 方法会根据指定的分隔符将字符串分割,并返回一个包含所有子串的列表。如果不指定分隔符,默认会使用空格作为分隔符。
实例
# 示例字符串
text = "Hello World, this is Python"
# 使用 split() 方法分割字符串
result = text.split()
# 输出结果
print(result)
text = "Hello World, this is Python"
# 使用 split() 方法分割字符串
result = text.split()
# 输出结果
print(result)
代码解析:
text = "Hello World, this is Python":定义一个字符串text。result = text.split():使用split()方法将字符串text按照空格分割成多个子串,并将结果存储在result列表中。print(result):输出分割后的结果。
输出结果:
['Hello', 'World,', 'this', 'is', 'Python']
在这个例子中,字符串 text 被分割成了 5 个子串,分别是 'Hello', 'World,', 'this', 'is', 和 'Python'。
Python3 实例
点我分享笔记