【问题标题】:Replacing parenthesis and spaces with an underscore without using replace functions (for loop format)用下划线替换括号和空格而不使用替换函数(for循环格式)
【发布时间】:2021-01-10 12:21:41
【问题描述】:

如何使用 Python 在 for 循环中将 () 和 " " 替换为 "_"?我了解 for 循环的基础知识。就像,i 代表字符串中的每个元素。我确实感觉有点模糊,因为它变得越来越复杂。但我需要帮助将() 和空格" " 替换为"_"。我的第一个想法是我可以将i 等同于() 和空格:i == "()" + " "。但我不知道如何添加"_" 来替换没有replace 函数的元素。感谢您的任何意见。

【问题讨论】:

  • 在提出这样一个很容易搜索并且肯定是重复的问题之前,您应该遵循教程或参加课程。从that 开始,如果您仍然不明白,请提出新问题并向我们展示您的尝试。

标签: python for-loop replace


【解决方案1】:

试试这个:

input_string='abcd(123) abc )( 456'
output_string= ''

for x in input_string:
    if(x != '(' and x != ')' and x != ' '):
        output_string += x
    else:
        output_string += '_'

print(f'input_string: {input_string}')
print(f'output_string: {output_string}')

【讨论】:

    【解决方案2】:
    string = "This is an (example)"
    l = list(string)
    
    for i in range(0,len(l)):
        if l[i] in ['(',')',' ']:
            l[i] = '_'
    
    string = "".join(l)
    

    将返回This_is_an__example_。但是,我不明白您不使用 str.replace 方法的动机。

    【讨论】:

      【解决方案3】:

      你可以这样做:

      new_str = ''
      your_str = 'abc()de f g'
      for x in your_str:
          if x in ['(',')',' ']:
              new_str+='_'
          else:
              new_str+=x
      

      【讨论】:

        猜你喜欢
        • 2014-11-27
        • 2011-07-12
        • 2020-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-11
        • 2010-11-03
        相关资源
        最近更新 更多