在Python中创建一个字符串替换循环

时间:2014-11-20 22:12:05

标签: python string function loops replace

我对python和编程很新,所以请耐心等待。 我正在尝试创建一个函数,它将获取给定的字符串输入并删除单词之间包含的任何空格。

我现在的代码:

def convertName(oldName):
    newName = oldName
    while newName == oldName:
        newName = oldName.replace("  "," ",)
    return newName

name = str(input("Name ---- "))
newName = convertName(name)
print("Result --",newName)

目前,我使这个循环工作的所有尝试都导致过程只进行一次,或者是无限循环。我理解,只要我的循环第一次运行newName不再等于oldName,所以我的while语句现在为false。任何提示/提示将非常感谢!!

3 个答案:

答案 0 :(得分:1)

正如您所说while条件为false,更好的解决方法是split字符串并与一个空格连接:

>>> s= 'a  b b   r'
>>> ' '.join(s.split())
'a b b r'

如果您不确定可以使用正则表达式的空格数:

>>> re.sub(r'\s+',' ',s)
'a b b r' 

\s+匹配任何空白组合!

答案 1 :(得分:0)

工作太多了。

newname = re.sub('  +', ' ', oldname)

答案 2 :(得分:0)

如果字符串中没有任何双重空格,newName将始终等于oldName。自上次以来没有更改,而不是替换,当上次自 发生更改时,您需要停止替换。

def convert_name(old_name):
    while True:
        # Replace any double-spaces in the current string
        new_name = old_name.replace('  ', ' ')

        if new_name == old_name:
            # String isn’t changing anymore, so there were
            # no double-spaces; return
            return new_name

        # Check the next replacement against this version
        old_name = new_name

正则表达式在这里工作得更好:

import re

def convert_name(name):
    return re.sub(' {2,}', ' ', name)