[英]Get content of string before '+' character in python
INPUT:输入:
s = 'Coated tablet + ALFUZOSIN HYDROCHLORIDE, Film-coated tablet + ALFUZOSIN HYDROCHLORIDE, Modified-release tablet + ALFUZOSIN HYDROCHLORIDE, Prolonged-release tablet + ALFUZOSIN HYDROCHLORIDE'
EXPECTED OUTPUT:预期产出:
s = 'Coated tablet, Film-coated tablet, Modified-release tablet, Prolonged-release tablet'
For each string like this, how do I get the necessary output in Python so that all elements after the + doesn't come.对于这样的每个字符串,我如何在 Python 中获得必要的输出,以便 + 之后的所有元素都不会出现。
Do split on ,
and then on +
and fetch item at index 0
拆分 on
,
然后拆分+
并在索引0
处获取项目
', '.join([i.split("+")[0].strip() for i in s.split(",")])
Output输出
'Coated tablet, Film-coated tablet, Modified-release tablet, Prolonged-release tablet'
Using regular expressions,使用正则表达式,
It removes from +
until it runs out of characters that aren't a comma它从
+
删除,直到用完不是逗号的字符
import re
s = 'Coated tablet + ALFUZOSIN HYDROCHLORIDE, Film-coated tablet + ALFUZOSIN HYDROCHLORIDE, Modified-release tablet + ALFUZOSIN HYDROCHLORIDE, Prolonged-release tablet + ALFUZOSIN HYDROCHLORIDE'
re.sub(" [+] [^,]+","",s)
Using regular expression:使用正则表达式:
import re
old_s = 'Coated tablet + ALFUZOSIN HYDROCHLORIDE, Film-coated tablet + ALFUZOSIN HYDROCHLORIDE, Modified-release tablet + ALFUZOSIN HYDROCHLORIDE, Prolonged-release tablet + ALFUZOSIN HYDROCHLORIDE'
new_s = re.sub(r'\s\+.*?, | \+.*?$', ',', s)[:-1]
print(new_s)
>>> 'Coated tablet, Film-coated tablet, Modified-release tablet, Prolonged-release tablet'
On the left hand of the pipe \\s
indicates white space, \\+.*?,
looks for everything between a +
and a ,
, on the right side, you're going for the end case where there is no comma, using $
instead.在管道的左侧,
\\s
表示空格, \\+.*?,
查找+
和 a 之间的所有内容,
,在右侧,您将寻找没有逗号的结尾情况,使用$
反而。
[:-1]
because all matches are replaced by a comma, however, you don't want the comma at the end of your string. [:-1]
因为所有匹配项都被逗号替换,但是,您不希望字符串末尾有逗号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.