如何每 3 个索引切片一个字符串? [英] How do I slice a string every 3 indices?

查看:31
本文介绍了如何每 3 个索引切片一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Python 为我工作的实验室编程.如何切出给定字符串中的每 3 个字符并将其附加到列表中?

即XXXxxxXXXxxxXXXxxxXXXxxxXXX(其中 X 或 x 是任何给定的字母)

string = 'XXXxxxXXXxxxXXXxxxXXXxxxXXX'我的列表 = []对于字符串中的 x:细绳[?:?:?]mylist.append(string)

我希望列表看起来像这样:['XXX','xxx','XXX','xxx','XXX'...等]

有什么想法吗?

解决方案

总之,你不能.

在更长的时间内,您可能需要编写自己的函数:

def split(str, num):返回 [ str[start:start+num] 开始在 range(0, len(str), num) ]

例如:

<前>>>> split("xxxXXX", 3)['xxx', 'XXX']>>> split("xxxXXXxx", 3)['xxx', 'XXX', 'xx']

I'm using Python to program for the lab I work at. How can I slice out every 3 characters in a given string and append it to a list?

i.e. XXXxxxXXXxxxXXXxxxXXXxxxXXX (where X or x is any given letter)

string = 'XXXxxxXXXxxxXXXxxxXXXxxxXXX'
mylist = []

for x in string:
    string[?:?:?]
    mylist.append(string)

I want the list to look like this: ['XXX','xxx','XXX','xxx','XXX'....etc]

Any ideas?

解决方案

In short, you can't.

In longer, you'll need to write your own function, possibly:

def split(str, num):
    return [ str[start:start+num] for start in range(0, len(str), num) ]

For example:

>>> split("xxxXXX", 3)
['xxx', 'XXX']
>>> split("xxxXXXxx", 3)
['xxx', 'XXX', 'xx']

这篇关于如何每 3 个索引切片一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆