且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用单个空格替换字符串中的多行距 - Python

更新时间:2023-11-04 22:12:10

看看这个

In [1]: str1 = "This is    a  foo bar   sentence with  crazy spaces that  irritates   my program "

In [2]: ' '.join(str1.split())
Out[2]: 'This is a foo bar sentence with crazy spaces that irritates my program'

方法 split() 返回字符串中所有单词的列表,使用 str 作为分隔符(如果未指定,则拆分所有空格)

The method split() returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified)