Python – 在所有标点符号上拆分字符串
给定一个字符串,在所有标点符号上拆分字符串。
Input : test_str = ‘geeksforgeeks! is-best’
Output : [‘geeksforgeeks’, ‘!’, ‘is’, ‘-‘, ‘best’]
Explanation : Splits on ‘!’ and ‘-‘.
Input : test_str = ‘geek-sfo, rgeeks! is-best’
Output : [‘geek’, ‘-‘, ‘sfo’, ‘, ‘, ‘rgeeks’, ‘!’, ‘is’, ‘-‘, ‘best’]
Explanation : Splits on ‘!’, ‘, ‘ and ‘-‘.
方法:使用正则表达式 + findall()
这是可以解决此问题的一种方法。在此,我们构造了适当的正则表达式,分离和拆分任务由 findall() 完成。
Python3
# Python3 code to demonstrate working of
# Split String on all punctuations
# using regex + findall()
import re
# initializing string
test_str = 'geeksforgeeks ! is-best, for @geeks'
# printing original String
print("The original string is : " + str(test_str))
# using findall() to get all regex matches.
res = re.findall( r'\w+|[^\s\w]+', test_str)
# printing result
print("The converted string : " + str(res))
输出
The original string is : geeksforgeeks! is-best, for @geeks
The converted string : ['geeksforgeeks', '!', 'is', '-', 'best', ', ', 'for', '@', 'geeks']