简体   繁体   English

如何将字符串拆分为连续的子字符串,例如:string_inputs: IN PYTHON3

[英]how can I split strings into continuous substrings e.g: string_inputs: IN PYTHON3

how can I split strings into continuous sub strings eg: string_inputs:如何将字符串拆分为连续的子字符串,例如: string_inputs:

AAAATTTT ATATATAT

output_needed:输出_需要:

AA,AA,AA,AT,TT,TT,TT
string_inputs = "AAAATTTTATATATAT"

#Note the `len(string_inputs) - 1` in the range; do according to what you desire as your output
d_out = [string_inputs[i:i+2] for i in range(0, len(string_inputs) - 1)]

d_out = ['AA', 'AA', 'AA', 'AT', 'TT', 'TT', 'TT', 'TA', 'AT', 'TA', 'AT', 'TA', 'AT', 'TA', 'AT']

You can obtain every two substrings with zip() here:您可以在此处使用zip()获取每两个子字符串:

>>> string = 'AAAATTTTATATATAT'
>>> ','.join(x + y for x, y in zip(string, string[1:]))
'AA,AA,AA,AT,TT,TT,TT,TA,AT,TA,AT,TA,AT,TA,AT'

This is also another way:这也是另一种方式:

>>> ','.join(map(''.join, zip(string, string[1:])))
'AA,AA,AA,AT,TT,TT,TT,TA,AT,TA,AT,TA,AT,TA,AT'

Or even something like this:或者甚至是这样的:

>>> ','.join(map(lambda x, y: x + y, string, string[1:]))
'AA,AA,AA,AT,TT,TT,TT,TA,AT,TA,AT,TA,AT,TA,AT'

This does what you're looking for.这就是你要找的。

string = "AAAATTTTATATATAT"
step = 2
split = [string[i:i+step] for i in range(0, len(string), step)]
print(",".join(split))

step is the chunk you want to split your string into. step是您要将字符串拆分成的块。 And the last line joins it with the , as in your example to give you the final output AA,AA,TT,TT,AT,AT,AT,AT最后一行将它与,如您的示例中所示,为您提供最终输出AA,AA,TT,TT,AT,AT,AT,AT

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在python中将包含撇号和数字的列表转换为数字(例如['2,2.4,3']到[2,2.4,3]) - how can I convert a list containing apostrophe and numbers to numbers (e.g ['2,2.4,3'] to [2,2.4,3]) in python 如何在Python3中获取/分割多个字符串输入 - How do you obtain/split multiple string inputs in Python3 Python:我可以将 dataframe 列中标记为“未知”的缺失值替换为 NaN 吗? - Python: Can I replace missing values marked as e.g "Unknown" to NaN in a dataframe column? 如何在Web服务器上运行Python脚本(例如localhost) - How to run Python scripts on a web server (e.g localhost) 如何制作由(例如)3 的倍数组成的 Python 阵列? - How do I make a Python array made up of multiples of (e.g) 3? 如何重命名内置函数,例如“if”->“hehe”、“elif”->“haha”、“else”->“hihi”? - How can I rename builtin functions e.g "if" -> "hehe", "elif" -> "haha", "else" -> "hihi"? 如何使用套接字发送不是字符串的内容? 例如,与客户端截屏并将其发送到服务器 - How do I send things that aren't strings with sockets? E.g taking a screenshot with the client and sending it to the server python中的递归,例如insertionsort - Recursion in python, e.g insertionsort 使用 Python 中的子字符串拆分字符串 - Split string with substrings in Python 如何拆分字符串并将其子字符串与子字符串列表相匹配? - Python - How to split a string and match its substrings to a list of substrings? - Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM