简体   繁体   English

如何在子字符串后捕获一定数量的字符?

[英]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.

相关问题 Python 在特定单词后捕获特定数字 - Python Capture certain number after certain words 您如何找到 substring 的所有实例,后跟一定数量的动态字符? - How do you find all instances of a substring, followed by a certain number of dynamic characters? 如何删除字符串中最后一个数字之后的所有内容(某些字符除外) - How to remove everything (except certain characters) after the last number in a string Python Substring - 将第 n 个字符拆分到某个字符串的左侧 - Python Substring - Splitting nth number of Characters to the left of a certain string 如何在Python中删除以某些字符开头和结尾的子字符串 - How to remove a substring that starts and ends with certain characters in Python 某些字符之间的正则表达式捕获 - Regex capture between certain characters 如何在字符串中的其他某些字符之后替换某些字符,Python? - How to replace certain characters after other certain characters in a string, Python? 如何在字符串的开头删除一定数量的字符 - How to remove a certain number of characters at the start of a string 如何在一定数量的非空格和非段落字符后拆分文本? - How to split text after a certain number of non-space and non-paragraph characters? 如何从具有相同后缀的 python 中的 substring 中提取特定数量的字符 - How to extract specific number of characters from a substring in python with same suffix
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM