【问题标题】:In need to capitalize the 3rd letter of this string [duplicate]需要将此字符串的第三个字母大写[重复]
【发布时间】:2020-10-27 12:59:48
【问题描述】:
x=input("enter word=")
if x[2]=="a":
x[2]="A"

如果您知道如何创建一个函数来将单词的每个偶数位置大写,也可以提供帮助。To Make It Like THiS

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    尝试将字符串x的第三个字母大写:

    x = input("enter word=")
    if x[2].islower():
        x = x[:2] + x[2].upper() + x[3:]
    

    【讨论】:

    • Thnx,你能解释一下最后一行的逻辑吗,我明白 .isupper 或 .is 较低,但是 [:2 :3] 是什么,为什么全部添加?
    • @NasrUllah 这是字符串连接。如果第 3 个字符是小写的,我们取前 2 个字符,大写第 3 个字符,然后取其余字符,然后将它们连接起来形成一个新字符串并将其分配给 x
    【解决方案2】:

    你可以这样做 -

    x2=x[:2] + x[2].upper() + x[3:]

    【讨论】:

      【解决方案3】:

      capitalise 功能将帮助您将每个单词的第三个字符大写。如果 word 少于 3 个字符,那么它将不加修改地返回字符串。

      def capitalise(x):
        chars = list(x)
        if len(x) > 2:
          chars[2] = chars[2].upper()
        return ''.join(chars)
      
      x = raw_input("enter word=")
      x = capitalise(x)
      print(x)
      

      【讨论】:

        【解决方案4】:
        x=input("enter word=")
        if len(x)>3:
           x = x[:2] + x[2].upper() + x[3:]
        

        你应该检查字符串的长度,否则如果单词少于3个字符就会出错

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-02-21
          • 1970-01-01
          • 2017-03-20
          • 2018-01-03
          • 2014-11-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多