📜  Python - 拆分字符串忽略空格格式化字符

📅  最后修改于: 2022-05-13 01:54:21.026000             🧑  作者: Mango

Python - 拆分字符串忽略空格格式化字符

给定一个字符串,拆分为单词,忽略空格格式化字符,如 \n、\t 等。

方法一:使用 re.split()

在此,我们采用由空格字符组成的适当正则表达式,并使用 split() 对正则表达式字符集进行拆分。

Python3
# Python3 code to demonstrate working of
# Split Strings igoring Space characters
# Using re.split()
import re
 
# initializing string
test_str = 'geeksforgeeks\n\r\t\t\nis\t\tbest\r\tfor geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# space regex with split returns the result
res = re.split(r'[\n\t\f\v\r ]+', test_str)
     
# printing result
print("The split string : " + str(res))


Python3
# Python3 code to demonstrate working of
# Split Strings igoring Space characters
# Using split()
 
# initializing string
test_str = 'geeksforgeeks\n\r\t\t\nis\t\tbest\r\tfor geeks'
 
# printing original string
print("The original string is : " + str(test_str))
     
# printing result
print("The split string : " + str(test_str.split()))


输出:

The original string is : geeksforgeeks

        
is        best
    for geeks
The split string : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']

方法 2:使用 split()

split()函数默认在空白处拆分字符串。

蟒蛇3

# Python3 code to demonstrate working of
# Split Strings igoring Space characters
# Using split()
 
# initializing string
test_str = 'geeksforgeeks\n\r\t\t\nis\t\tbest\r\tfor geeks'
 
# printing original string
print("The original string is : " + str(test_str))
     
# printing result
print("The split string : " + str(test_str.split()))

输出:

The original string is : geeksforgeeks

        
is        best
    for geeks
The split string : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']