[英]How to capture a certain number of characters after a substring?
I'm very new to coding and need help on one last question of an assignment that has me stumped. 我对编码非常陌生,需要帮助解决一个令我难过的作业的最后一个问题。 I can't use regular expressions for this assignment, either.
我也不能将正则表达式用于此赋值。
I've got this string, and I've made it so I split the string after 'cat'
occurs. 我有这个字符串,我已经做了所以我在
'cat'
出现后拆分了字符串。
astr = 'accaggcatgattgcccgattccatgcggtcag'
x = astr.split('cat',1)[-1]
print(x)
gattgcccgattccatgcggtcag
y = astr.split('cat',2)[-1]
print(y)
gcggtcag
However, what can I do if I only want the three letters after each 'cat'
in the string? 但是,如果我只想在字符串中每个
'cat'
后面的三个字母,我该怎么办? For example, I'd want to get 'gat'
and 'gcg'
. 例如,我想要
'gat'
和'gcg'
。
Any help is greatly appreciated! 任何帮助是极大的赞赏!
Use slicing, like [:3]
: 使用切片,如
[:3]
:
astr = 'accaggcatgattgcccgattccatgcggtcag'
x = astr.split('cat',1)[-1][:3]
print(x)
y = astr.split('cat',2)[-1][:3]
print(y)
Output: 输出:
gat
gcg
Also, another idea could be: 另外,另一个想法可能是:
print(list(map(lambda x: x[:3],astr.split('cat')[1:])))
You can also get all of them in one go: 您也可以一次性获得所有这些:
[x[:3] for x in astr.split('cat')[1:]]
Output: 输出:
['gat', 'gcg']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.