【问题标题】:Python: String iteration replace a space with a hyphen (or other character)Python:字符串迭代用连字符(或其他字符)替换空格
【发布时间】:2018-09-19 08:14:25
【问题描述】:

我需要遍历字符串“work_tip”并将每个字母发布到变量“new_string”。这工作正常。但是,我需要用连字符替换空格或将其完全连接起来。这是我研究的一部分,所以我不能使用其他一些可能更好的语法解决方案。我知道这将是非常简单的插入到下面的内容,但我无法弄清楚在寻找空间和执行附加功能时要采取的额外步骤。

work_tip = "Good code is commented code"
new_string = ""

for letter in work_tip:
    new_string += letter
print(new_string)

期望的输出:好的代码是注释代码

【问题讨论】:

  • 在打印之前添加new_string.replace(' ', '-')
  • 所以你问如何检查一个字符是否为空格?

标签: python string loops


【解决方案1】:
work_tip = "Good code is commented code"
new_string = work_tip.replace(' ', '-')
print(new_string)

【讨论】:

    【解决方案2】:

    非常感谢大家的回复(这是我的第一个 Stack 问题 :))。我怀疑有一个非常直接的解决方案,但是对于“替换”,我实际上还不允许使用该语法,因为它没有包含在当前模块中。

    我最终还是设法到达了那里(而且它很冗长,因为我们希望只使用我们已经介绍过的语法来回答。对于任何好奇的人,请参阅下文;

    work_tip = "Good code is commented code"
    new_string = ""
    for letter in work_tip:
        if letter.isalpha():
            new_string = new_string + letter
        else:
            new_string = new_string + "-"
    
    print(new_string)
    

    对于一些包含三行内容的内容相当冗长,但总有一天我会到达那里。

    再次感谢大家!

    埃德

    【讨论】:

      【解决方案3】:

      以下是解决方案。你也可以试试这个。

      work_tip = "Good code is commented code"
      
      new_string = " "
      
      for letter in work_tip:
      
          if letter.find(" "):
      
              new_string = new_string + letter
          else:
      
              new_string = new_string + "-"
      
      print(new_string)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-04
        • 1970-01-01
        • 2018-04-27
        • 2021-05-11
        • 2020-12-19
        • 1970-01-01
        • 1970-01-01
        • 2017-01-02
        相关资源
        最近更新 更多