格式化字符串只在python中的单词之间有n个空格

我正在使用非空白字符之间具有不同空格数的字符串.问题是这个字符串形成一个类别,它们必须相同.我想将它们格式化为在非空白字符之间具有完全相同的空格数,例如. 1,但如果可能,这可以推广到插入更多空格.并且在开头和结尾都不应该有空格.

n = 1的示例:

'a  b    b' => 'a b c'
'  a b   c  ' => 'a b c'

最佳答案 只需将其拆分并按空格加入结果列表即可

>>> " ".join('a  b    b'.split())
'a b c'
>>> "  ".join('  a b   c  '.split())
'a  b  c'

来自str.split(sep)文档:

If sep is not specified or is None, a different splitting algorithm is
applied: runs of consecutive whitespace are regarded as a single
separator, and the result will contain no empty strings at the start
or end if the string has leading or trailing whitespace.

点赞