基于关键字和固定长度使用 python 的子字符串
substring using python based on key word and fixed length
我有一个很长的字符串,这只是其中的一部分:
s = 'States AL Date 2011 01 03 YES States MD Date 2009 08 09 NO'
如何对它们进行子字符串化以使输出为:
'States AL Date 2011 01 03 YES', 'States MD Date 2009 08 09 NO'...
每个子字符串以关键字“States”开头,长度固定为 30。谢谢!
您想使用正则表达式搜索。
import re
s = 'States AL Date 2011 01 03 YES States MD Date 2009 08 09 NO'
results = re.findall('States [A-Z]{2} Date \d{4} \d{2} \d{2} (?:YES|NO)', s)
如果您只想从每个 'States' 个子字符串开始长度为 30 的子字符串:
import re
s = 'States AL Date 2011 01 03 YES States MD Date 2009 08 09 NO'
results = [s[m.start():m.start()+30] for m in re.finditer('States', s)]
我有一个很长的字符串,这只是其中的一部分:
s = 'States AL Date 2011 01 03 YES States MD Date 2009 08 09 NO'
如何对它们进行子字符串化以使输出为:
'States AL Date 2011 01 03 YES', 'States MD Date 2009 08 09 NO'...
每个子字符串以关键字“States”开头,长度固定为 30。谢谢!
您想使用正则表达式搜索。
import re
s = 'States AL Date 2011 01 03 YES States MD Date 2009 08 09 NO'
results = re.findall('States [A-Z]{2} Date \d{4} \d{2} \d{2} (?:YES|NO)', s)
如果您只想从每个 'States' 个子字符串开始长度为 30 的子字符串:
import re
s = 'States AL Date 2011 01 03 YES States MD Date 2009 08 09 NO'
results = [s[m.start():m.start()+30] for m in re.finditer('States', s)]