Python 加上:&引用;对于列表中的每n个字符

Python 加上:&引用;对于列表中的每n个字符,python,python-3.x,Python,Python 3.x,假设我有这个: x = ["hello-543hello-454hello-765", "hello-745hello-635hello-321"] 如何将输出获取到: ["hello-543: hello-454: hello-765", "hello-745: hello-635: hello-321"] 您可以使用range根据子字符串长度拆分每个字符串,其中步长值是每个子字符串应包含的字符数。然后使用join将每个列表转换回具有所需分隔符的字符串 x = ["hello-543hel

假设我有这个:

x = ["hello-543hello-454hello-765", "hello-745hello-635hello-321"]
如何将输出获取到:

["hello-543: hello-454: hello-765", "hello-745: hello-635: hello-321"]

您可以使用
range
根据子字符串长度拆分每个字符串,其中步长值是每个子字符串应包含的字符数。然后使用
join
将每个列表转换回具有所需分隔符的字符串

x = ["hello-543hello-454hello-765", "hello-745hello-635hello-321"]

n = 9
result = [': '.join([s[i:i+n] for i in range(0, len(s), n)]) for s in x]
print(result)
# ['hello-543: hello-454: hello-765', 'hello-745: hello-635: hello-321']
或与:


如果您确定每个
str
长度都是您的
n
的倍数,我将使用
re.findall
来完成该任务

import re
txt1 = "hello-543hello-454hello-765"
txt2 = "hello-745hello-635hello-321"
out1 = ": ".join(re.findall(r'.{9}',txt1))
out2 = ": ".join(re.findall(r'.{9}',txt2))
print(out1) #hello-543: hello-454: hello-765
print(out2) #hello-745: hello-635: hello-321

{9}
中的
re.findall
表示除换行符(
\n
)以外的任何字符的
9
,因此只要
str
不包含
\n
,此代码将正常工作。如果这不成立,您需要添加
re.DOTALL
作为
re.findall

从输入到输出的第三个参数?你试过什么?你会犯什么错误?你有更实际的例子吗?或者你会在实际的列表中重复单词吗?如果所有的单词都不一样,我的一个修正就不起作用了。它们都有相同的字符长度,但不同的字符,我在上面创建了一个更好的例子
import re
txt1 = "hello-543hello-454hello-765"
txt2 = "hello-745hello-635hello-321"
out1 = ": ".join(re.findall(r'.{9}',txt1))
out2 = ": ".join(re.findall(r'.{9}',txt2))
print(out1) #hello-543: hello-454: hello-765
print(out2) #hello-745: hello-635: hello-321