Python 如何按空格拆分字符串

Python 如何按空格拆分字符串

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

第一种方法是使用内置的函数 split() 。该方法将给定的字符串按指定的分隔符拆分。 split() 方法接受一个名为delimiter的参数,它指定字符串应该在什么字符处拆分。

因此,我们需要将空格作为分隔符发送给 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']

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程