在Python中创建字符串替换循环
一般来说,我对python和编程相当陌生,所以请容忍我。 我试图创建一个函数,该函数将接受给定的字符串输入,并删除单词之间包含的任何空格 我现在的代码是:在Python中创建字符串替换循环,python,string,function,loops,replace,Python,String,Function,Loops,Replace,一般来说,我对python和编程相当陌生,所以请容忍我。 我试图创建一个函数,该函数将接受给定的字符串输入,并删除单词之间包含的任何空格 我现在的代码是: def convertName(oldName): newName = oldName while newName == oldName: newName = oldName.replace(" "," ",) return newName name = str(input("Name ---- "
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。任何提示/提示都将不胜感激 工作太多了
newname = re.sub(' +', ' ', oldname)
如果字符串中没有任何双空格开头,
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)
正如您所说,您的
while
条件为false,解决此问题的更好方法是拆分
字符串并用一个空格连接:
>>> s= 'a b b r'
>>> ' '.join(s.split())
'a b b r'
如果不确定空间的数量,可以使用正则表达式:
>>> re.sub(r'\s+',' ',s)
'a b b r'
\s+
匹配任意组合的空格 嘿,这个解决方案很有效,我现在只有一个问题。如果newName的输入在其前面包含X个空格,print语句也会在名称前面显示1个空格。例如:如果newName=Josh示例它打印:Josh示例但是,如果我在“Josh”之前加上任意数量的空格,我的打印结果将在名称之前包含1个空格。newName=Josh-example-example-print(newName)产生:Josh-example-example有什么想法吗?然后你需要再做一次,用'^+'
替换'
。我替换的是哪个部分?我不认为有一个“^+”嗯,我仍然无法产生正确的结果。我试过你的几种变体。你能给出一些提示而不给出答案吗?谢谢你的帮助。…=re.sub(“^+”,…)