如何每 3 个索引对字符串进行切片?
我正在使用 Python 为我工作的实验室编程。如何切出给定字符串中的每 3 个字符并将其附加到列表中?
即 XXXxxxXXXxxxXXXxxxXXXxxxXXX (其中 X 或 x 是任何给定的字母)
string = 'XXXxxxXXXxxxXXXxxxXXXxxxXXX'
mylist = []
for x in string:
string[?:?:?]
mylist.append(string)
我希望列表如下所示: ['XXX','xxx','XXX','xxx','XXX'....等]
有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简而言之,你不能。
更长的时间,您可能需要编写自己的函数:
例如:
In short, you can't.
In longer, you'll need to write your own function, possibly:
For example:
将列表拆分为 3 个块和将字符串拆分为 3 个块之间的一个区别是 re 模块适用于字符串而不是列表。
如果性能很重要(即您要分割数千个字符串),您应该测试如何在应用程序中比较各种答案。
这之所以有效,是因为
.
表示正则表达式中的“匹配任何字符”。.{3}
表示“匹配任意3个字符”,依此类推one difference between splitting lists into chunks of 3 and strings into chunks of 3 is that the re module works with strings rather than lists.
If performance is important (ie you are splitting thousands of strings), you should test how the various answers compare in your application
This works because
.
means "match any character" in regular expressions..{3}
means "match any 3 characters", and so on据我所知,没有内置方法可以让您对每个 x 索引对 str 进行分块。然而这应该有效:
产生:
As far as I know there is no built in method that allows you to chunk an str every x indices. However this should works:
produces:
从 2008 年 11 月起复制 How do you split a list into equal-sized chunks in Python? 的答案:
直接来自 Python 文档(食谱for itertools):
另一种方式,正如 JFSebastian 所建议的:
我猜 Guido 的时间机器可以工作——工作——将工作——将工作——再次工作。
Copying an answer from How do you split a list into evenly sized chunks in Python? since Nov 2008:
Directly from the Python documentation (recipes for itertools):
An alternate take, as suggested by J.F.Sebastian:
I guess Guido's time machine works—worked—will work—will have worked—was working again.