【问题标题】:Creating a string replacement loop in Python在 Python 中创建字符串替换循环
【发布时间】:2014-11-20 22:12:04
【问题描述】:

我对 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 语句现在是错误的。任何提示/提示将不胜感激!

【问题讨论】:

    标签: python string function loops replace


    【解决方案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+ 匹配任何空格组合!

    【讨论】:

      【解决方案2】:

      工作量太大。

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

      【讨论】:

      • 嘿,这个解决方案效果很好,我现在只有一个问题。如果 newName 的输入在其前面包含 X 个空格,则 print 语句还会在名称前显示 1 个空格。例如:如果 newName = Josh example example 它打印: Josh example example 但是,如果我在“Josh”之前放置任意数量的空格,我的打印结果将在名称前包含 1 个空格。 newName = Josh 示例 print(newName) 产生: Josh 示例 有什么想法吗?
      • 那你需要再做一次,用''代替'^ +'
      • 我替换的是哪个部分?我认为没有'^ +'
      • 嗯,我仍然无法产生正确的结果。我已经尝试了你所拥有的几种变体。您可以在不给出答案的情况下给出任何提示吗?感谢您的帮助。
      • ... = re.sub('^ +', ...)
      【解决方案3】:

      如果字符串开头没有任何双空格,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)
      

      【讨论】:

        猜你喜欢
        • 2012-09-25
        • 2019-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-08
        • 2015-04-25
        • 2020-12-18
        • 1970-01-01
        相关资源
        最近更新 更多