简体   繁体   English

如何在特定字符后分割字符串?

[英]how to split a string after a specific character?

I want to split a list of items with specific symbol. 我想用特定符号拆分项目列表。

I have used the following code 我使用了以下代码

data = "launch,  7:30am,  watch tv,  workout,  snap,  running,  research study and learn"
items = data.split(',')
print(', '.join([items[0], items[-1].split('—')[1]]))

Here what I wanted is that to split this data and print like this: 我想要的是拆分数据并像这样打印:

launch, study and learn 发射,学习和学习

but a problem appears when data changed like this: 但是,当数据按以下方式更改时出现问题:

data = "launch, 7:30am, watch tv, workout, snap, running, research — discussion, study and learn"
items = data.split(',')
print(', '.join([items[0], items[-1].split('—')[1]]))

and in this I case I expected to get this result: 在这种情况下,我期望得到以下结果:

launch, discussion, study and learn 发起,讨论,学习

as such, an error appears "list index out of range"! 因此,出现错误“列表索引超出范围”! that is right because there is no symbol "-" after last element, because of "," and I instructed data to be splitted as "," therefore in "discussion, study and learn" will be treated as separate data so an error appears. 这是正确的,因为最后一个元素后没有符号“-”,因为是“,”,并且我指示将数据拆分为“,”因此在“讨论,学习和学习”中将其视为单独的数据,因此会出现错误。 I wanted to not rewrite any code, is it possible to use code reuse to read both data. 我不想重写任何代码,是否可以使用代码重用来读取两个数据。 is it possible to read after "-" symbol? 是否可以在“-”符号后面读取?

Seems like your expected output is dependent on word research 似乎您的预期输出取决于单词research

We can implement the same using regex which will search research word and gives you characters after it. 我们可以使用正则表达式来实现相同的功能,它将搜索research词并在其后给您提供字符。

You can try this - 你可以试试这个-

# -*- coding: utf-8 -*-
import re
(re.split(r'*research[^A-Za-z0-9]+',data))[-1]
#study and learn
#discussion, study and learn

Full Code: 完整代码:

# -*- coding: utf-8 -*-
import re
print ("{0}, {1}".format(data.split(',')[0], (re.split(r' *research[^A-Za-z0-9]+',data))[-1]))
#launch, study and learn
#launch, discussion, study and learn

Read more about python Regex : 阅读有关python Regex的更多信息:

https://docs.python.org/3/library/re.html https://docs.python.org/3/library/re.html

or about expressions here : 或关于此处的表达式:

https://www.w3schools.com/python/python_regex.asp https://www.w3schools.com/python/python_regex.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM