【问题标题】:Replace only the ending of a string仅替换字符串的结尾
【发布时间】:2018-12-11 19:37:34
【问题描述】:

不能在一行中完成以下操作让我很恼火。我感觉可以通过列表理解来完成,但是如何?

given_string = "first.second.third.None"
string_splitted = given_string.split('.')
string_splitted[-1] = "fourth"
given_string = ".".join(string_splitted)

请注意,给定字符串中的点数 (.) 是恒定的 (3)。所以我总是想替换字符串的第四个片段。

【问题讨论】:

  • 所以你的输出是first.second.third ?
  • 不,它的'first.second.third.fourth'
  • 可以在一行中做到这一点,但它并不漂亮。你那里有什么问题?把它放在一个函数中会比理解更好。
  • 我在 3 行中做了一个非常简单的事情,我感觉它可以减少。
  • 不...仅来自上一期repl.it/repls/RunnyIntentProspect

标签: python string list


【解决方案1】:

看来您应该能够在不拆分为数组的情况下做到这一点。找到最后一个. 并切到那里:

> given_string = "first.second.third.None"
> given_string[:given_string.rfind('.')] + '.fourth'

'first.second.third.fourth'

【讨论】:

  • 打败我!!
  • 只有 30 秒 @ParitoshSingh!
  • 我想知道这个和 Vasilis G. 建议的哪个更易读。
【解决方案2】:

你可以试试这个:

given_string = "first.second.third.None"
given_string = ".".join(given_string.split('.')[:-1] + ["fourth"])
print(given_string)

输出:

first.second.third.fourth

【讨论】:

    【解决方案3】:

    试试这个衬里:-

    print (".".join(given_string.split(".")[:-1]+["Fourth"]))
    

    输出:

    first.second.third.Fourth
    

    【讨论】:

      【解决方案4】:

      您可以使用 rsplit。无论最后一次分割之前有多少个点,这都会起作用

      given_string = "first.second.third.None"
      string_splitted = given_string.rsplit('.', 1)[0] + '.fourth'
      
      print(string_splitted)
      first.second.third.fourth
      

      【讨论】:

        【解决方案5】:
        my_string = "first.second.third.None"
        my_sub = re.sub(r'((\w+\.){3})(\w+)', r'\1fourth', my_string)
        print(my_sub)
        first.second.third.fourth
        

        对这种风格的一个很好的解释在这里:How to find and replace nth occurence of word in a sentence using python regular expression?

        【讨论】:

          最近更新 更多