简体   繁体   English

Python。 如何每隔n个字符用空格分隔字符串?

[英]Python. How to separate string with whitespace every nth character?

How would you insert a whitespace into a string after every nth term.您将如何在每第 n 个术语后向字符串中插入一个空格。 I need the output to still be a string, not a list.我需要输出仍然是一个字符串,而不是一个列表。

This is what i would want it to look like:这就是我希望它的样子:

message = ("xxxxxxxxxxxx")
output = ("xxxxx xxxxx xx") #E.g every 5 characters

*edit my question doesn't involve lists, only strings *编辑我的问题不涉及列表,只涉及字符串

>>> message = "xxxxxxxxxxxx"
>>>' '.join([message[i:i+5] for i in range(0, len(message), 5)])
'xxxxx xxxxx xx

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM