简体   繁体   中英

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.

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? For example, I'd want to get 'gat' and 'gcg' .

Any help is greatly appreciated!

Use slicing, like [: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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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