簡體   English   中英

為列表中的每個第 n 個字符添加“:”

[英]Add ": " for every nth character in a list

說我有這個:

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']

或者使用textwrap.wrap

from textwrap import wrap

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

n = 9
result = [': '.join(wrap(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} in re.findall表示除換行符 ( \\n ) 之外的任何字符的9 \\n ,因此只要您的str不包含\\n ,此代碼就可以正常工作。 如果這不成立,你需要添加re.DOTALL作為第三個參數re.findall

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM