如何在 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']
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP