如何在 Python 中按空格拆分字符串?


在本文中,我们将了解如何在 Python 中按空格拆分字符串。

第一种方法是使用内置方法 `split()`。此方法会根据我们想要的定界符拆分给定的字符串。`split()` 方法接受一个名为定界符的参数,它指定应在哪个字符处拆分字符串。

因此,我们必须将空格作为定界符发送到 `split()` 方法。此方法返回按空格拆分的修改后的列表。

示例

在下面的示例中,我们取一个字符串作为输入,并使用 `split()` 方法按空格拆分字符串

str1 = "Hello Everyone Welcome to Tutorialspoint"

print("The given string is")
print(str1)

print("The strings after the split are")
res = str1.split()
print(res)

输出

上面示例的输出如下所示

The given string is
Hello Everyone Welcome to Tutorialspoint
The strings after the split are
['Hello', 'Everyone', 'Welcome', 'to', 'Tutorialspoint']

使用 re.split() 函数

第二种技术使用正则表达式。导入 re 库,如果尚未安装,请安装它以使用它。导入 re 库后,我们可以在 re.split() 函数中使用正则表达式“s+”。`re.split()` 函数将正则表达式和字符串作为参数,并在正则表达式指定的字符处拆分字符串。

示例

在下面的示例中,我们取一个字符串作为输入,并使用正则表达式按空格拆分字符串

import re
str1 = "Hello Everyone Welcome to Tutorialspoint"

print("The given string is")
print(str1)

print("The strings after the split are")
res = re.split('\s+', str1)
print(res)

输出

上面示例的输出如下所示

The given string is
Hello Everyone Welcome to Tutorialspoint
The strings after the split are
['Hello', 'Everyone', 'Welcome', 'to', 'Tutorialspoint']

使用 re.findall() 函数

第三种方法是使用正则表达式的 `re.findall()` 方法。此方法查找所有不是空格的字符串,因此从技术上讲,它会在空格处拆分字符串。

示例

在下面的示例中,我们取一个字符串作为输入,并使用 `re.findall()` 方法按空格拆分字符串

import re
str1 = "Hello Everyone Welcome to Tutorialspoint"

print("The given string is")
print(str1)

print("The strings after the split are")
res = re.findall(r'\S+', str1)
print(res)

输出

上面示例的输出如下所示

The given string is
Hello Everyone Welcome to Tutorialspoint
The strings after the split are
['Hello', 'Everyone', 'Welcome', 'to', 'Tutorialspoint']

更新于:2022年12月7日

17K+ 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.