Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 784
Summer Avatar asked Oct 19 '25 05:10

Summer


2 Answers

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:])))
like image 173
U12-Forward Avatar answered Oct 21 '25 20:10

U12-Forward


You can also get all of them in one go:

[x[:3] for x in astr.split('cat')[1:]]

Output:

['gat', 'gcg']
like image 23
busybear Avatar answered Oct 21 '25 18:10

busybear



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!