[英]splitting string in Python (2.7)
I have a string such as the one below: 我有一个像下面这样的字符串:
26 (passengers:22 crew:4)
or 要么
32 (passengers:? crew: ?)
. 。 What I'm looking to do is split up the code so that just the numbers representing the number of passengers and crew are extracted.
我想做的是将代码分解,以便仅提取代表乘客和机组人员数量的数字。 If it's a question mark, I'd look for it to be replaced by a "".
如果这是一个问号,我希望将其替换为“”。
I'm aware I can use string.replace("?", "") to replace the ? 我知道我可以使用string.replace(“?”,“”)替换?。 however how do I go about extracting the numeric characters for crew or passengers respectively?
但是,如何分别提取机组人员或乘客的数字字符? The numbers may vary from two digits to three so I can't slice the last few characters off the string or at a specific interval.
数字可能从两位到三位不等,因此我无法将字符串的最后几个字符切成一定的间隔。
Thanks in advance 提前致谢
A regular expression to match those would be: 与这些匹配的正则表达式为:
r'\(\s*passengers:\s*(\d{1,3}|\?)\s+ crew:\s*(\d{1,3}|\?)\s*\)'
with some extra whitespace tolerance thrown in. 还有一些额外的空白容忍度。
Results: 结果:
>>> import re
>>> numbers = re.compile(r'\(\s*passengers:\s*(\d{1,3}|\?)\s+ crew:\s*(\d{1,3}|\?)\s*\)')
>>> numbers.search('26 (passengers:22 crew:4)').groups()
('22', '4')
>>> numbers.search('32 (passengers:? crew: ?)').groups()
('?', '?')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.