【问题标题】:How do I implement " .count", ".replace", ".find", .rfind", into this line of code and have it so the two letter "r" is capitalized in the middle我如何在这行代码中实现 \" .count\", \".replace\", \".find\", .rfind\" 并让两个字母 \"r\" 大写中间
【发布时间】:2022-11-29 09:19:43
【问题描述】:
race = "The rabbit will run with the turtle in the race."

if you == "race":
  print("")
  print("Here is example 1!, 'R' is the chosen letter")
  print(race)
  print(race[5:race.find("r")] + race[:race.rfind("r")+4].replace("r", "R", 4).replace("R","r",1))

我如何将 .count.replace.find.rfind 实现到代码的最后一行,并使句子中字母 "r" 的第一个和最后一个实例保持小写,但中间两个"r"是大写吗?

预期输出:(使用 .count、.find、.rfind、.replace)

The rabbit will run with the turtle in the race.
The rabbit will Run with the tuRtle in the race.

【问题讨论】:

    标签: python


    【解决方案1】:

    与其在一个令人困惑的单行代码中执行此操作,不如让我们逐步执行此操作:

    1. 找到第一个和最后一个"r"的索引
      first_r = race.find("r")        # 4
      last_r = race.rfind("r")        # 43
      
      1. 对字符串进行切片,这样我们就有了我们需要的部分想要将字符与我们所做的部分分开。请记住切片结束结束索引(它们不包括结束索引)
      prefix = race[:first_r+1]       # 'The r'
      target = race[first_r+1:last_r] # 'abbit will run with the turtle in the '
      suffix = race[last_r:]          # 'race.'
      
      1. 替换target字符串中的字符
      target = target.replace("r", "R")  # 'abbit will Run with the tuRtle in the '
      
      1. 加入所有字符串:
      result = prefix + target + suffix 
      

      这给了我们预期的result

      'The rabbit will Run with the tuRtle in the race.'
      

      现在我们已经了解了执行此操作所涉及的步骤,我们可以将其压缩为更少的行:

      first_r = race.find("r")
      last_r = race.rfind("r")
      result = race[:first_r+1] + race[first_r+1:last_r].replace("r", "R") + race[last_r:]
      

      这不考虑原始字符串中只有一个 "r" 的情况。处理留给读者作为练习。提示:在这种情况下,“第一个”和“最后一个”r 的索引是什么?

    【讨论】:

    • 为了简化一点,您实际上只需要两个子字符串:直到并包括第一个 r 的所有内容,以及之后的所有内容。您可以在第二个子字符串上使用 .replace('r', 'R', count=2) 将替换字符的数量限制为 2。
    • @JohnGordon 这需要硬编码 rs 的数量来替换,我想避免这种情况。
    • @PranavHosangadi 是否可以添加“.count”,或者是否像我被告知的那样在代码中需要它?
    • @JamesLeroy .count 是不必要的。我能看到它被使用的唯一情况是确保字符串有两个以上的rs,所以你可以决定是通过这个逻辑还是只打印原始字符串。不过,实现它对您来说应该相当容易——参见documentation,它没有什么特别的——你给它一个子字符串来计数,它返回出现的次数。
    猜你喜欢
    • 2011-06-28
    • 1970-01-01
    • 2021-12-04
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    • 2018-12-10
    相关资源
    最近更新 更多