Python程序通过给定的字符串列表拆分字符串
给定一个字符串列表。任务是通过给定的字符串。
Input : test_str = ‘geekforgeeksbestforgeeks’, sub_list = [“best”]
Output : [‘geekforgeeks’, ‘best’, ‘forgeeks’]
Explanation : “best” is extracted as different list element.
Input : test_str = ‘geekforgeeksbestforgeeksCS’, sub_list = [“best”, “CS”]
Output : [‘geekforgeeks’, ‘best’, ‘forgeeks’, “CS”]
Explanation : “best” and “CS” are extracted as different list element.
方法:使用 re.split() + |运算符
在此,我们使用正则表达式 split() 和 | 执行拆分任务。运算符来检查所有需要单独放置的单词。
Python3
# Python3 code to demonstrate working of
# Separate specific Strings
# Using re.split() + | operator
import re
# initializing string
test_str = 'geekforgeeksisbestforgeeks'
# printing original String
print("The original string is : " + str(test_str))
# initializing list words
sub_list = ["best"]
# regex to for splits()
# | operator to include all strings
temp = re.split(rf"({'|'.join(sub_list)})", test_str)
res = [ele for ele in temp if ele]
# printing result
print("The segmented String : " + str(res))
输出
The original string is : geekforgeeksisbestforgeeks
The segmented String : ['geekforgeeksis', 'best', 'forgeeks']