【问题标题】:Finding and replacing a pair of characters in a string with another pair of characters in that string查找字符串中的一对字符并将其替换为该字符串中的另一对字符
【发布时间】:2016-04-03 02:43:35
【问题描述】:

我是 Python 新手,但想弄清楚如何获取一个字符串并交换成对的字符。假设我们有字符串 'HELLO__WORLD' 并想用 __ 切换 HELLO 中的 HE。这样字符串现在看起来像 '__LLOHEWORLD' 怎么可能呢?它与.pop 和.append 有什么关系吗?或者也许可以使用 if、elif、else 函数?也许一开始需要 .index 来查找用户指定需要交换的字符?

老实说,我真的不知道从哪里开始。

【问题讨论】:

  • string.replace("HE","__")string.replace("HELLO__WORLD","__LLO__WORLD")

标签: python string python-3.x swap


【解决方案1】:

正如其他答案中提到的,str.replace 绝对是您想要使用的:

my_string = "HELLO__WORLD"
replaced = my_string.replace("HE","__")
print(replaced) #shows __LLO__WORLD

尽管如果"HE" 出现在字符串中的其他位置并且不应被替换,这可能还不够:

my_string = "HE SAID HELLO_WORLD"
replaced = my_string.replace("HE","__")
print(replaced) #shows __ SAID __LLO_WORLD

在这种情况下,您需要指定要替换的整个部分:

my_string = "HE SAID HELLO_WORLD"
replaced = my_string.replace("HELLO_WORLD","__LLO__WORLD")
print(replaced) #shows HE SAID __LLO_WORLD

【讨论】:

    【解决方案2】:

    .pop().append()list 方法。

    阅读列表和数据结构https://docs.python.org/2/tutorial/datastructures.html

    你可以使用replace解决这个问题

    例如。

    hello = 'HELLO WORLD'
    new_hello = hello.replace('HE', '_')
    

    【讨论】:

    • 如果我将字符串转换为列表会怎样?那我可以使用 .pop() 和 .append() 吗?
    • 是的。如果将字符串转换为列表,则可以使用 .pop() 和 .append()。
    • 但是我该怎么做呢?
    【解决方案3】:

    查看replace字符串方法:

    s = 'HELLO__WORLD'
    s = s.replace('HE', '__')
    

    【讨论】:

      【解决方案4】:

      如果你有想要交换的子字符串的索引,你可以把你的字符串变成列表,用切片交换,然后再把它变成字符串。

      s = "HELLO__WORLD"
      # "HE" is at [0:2], "__" is at [5:7]
      s = list(s)
      s[0:2], s[5:7] = s[5:7], s[0:2]
      s = "".join(s)
      print(s) # prints __LLOHEWORLD
      

      要查找子字符串的索引,可以使用.find

      s = "HELLO__WORLD"
      s.find("__") #returns 5
      

      【讨论】:

      • 感谢 Miles,这真的很有帮助。
      猜你喜欢
      • 1970-01-01
      • 2012-07-16
      • 2017-06-16
      • 2021-06-15
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2012-09-11
      • 2011-11-16
      相关资源
      最近更新 更多