【问题标题】:Python How to capitalize nth letter of a stringPython如何将字符串的第n个字母大写
【发布时间】:2013-03-29 07:02:19
【问题描述】:

我试过这个:Capitalize a string。任何人都可以提供一个简单的脚本/sn-p 作为指南吗?

Python 文档有 capitalize() 函数,它使首字母大写。我想要make_nth_letter_cap(str, n)之类的东西。

【问题讨论】:

    标签: python string capitalize


    【解决方案1】:

    将第 n 个字符大写并将其余字符小写,如 capitalize() 所做的那样:

    def capitalize_nth(s, n):
        return s[:n].lower() + s[n:].capitalize()
    

    【讨论】:

      【解决方案2】:
      my_string[:n] + my_string[n].upper() + my_string[n + 1:]
      

      或者不是Schlemiel the Painter's algorithm的更高效的版本:

      ''.join([my_string[:n], my_string[n].upper(), my_string[n + 1:]])
      

      【讨论】:

      • 这里有更多关于python中字符串连接的信息stackoverflow.com/questions/12169839/…
      • 在您的情况下 N=3 ,因此我们无法确定 O(N) 或 O(N*N) 哪种实现会更“有效”(对于如此小的 N)。我不知道''.join([a, b, c])a+b+c 哪个更有效(或者是否值得担心将几个字符串相对于代码库中的其他部分连接起来所花费的时间)。
      【解决方案3】:
      x = "string"
      y = x[:3] + x[3].swapcase() + x[4:]  
      

      输出

      strIng  
      

      Code

      请记住,swapcase 将反转大小写,无论是小写还是大写。
      我用这个只是为了展示另一种方式。

      【讨论】:

      • 我在答案下方添加了注释
      【解决方案4】:

      我知道这是一个老话题,但这可能对将来的某人有用:

      def myfunc(str, nth):
      new_str = '' #empty string to hold new modified string
      for i,l in enumerate(str): # enumerate returns both, index numbers and objects
          if i % nth == 0: # if index number % nth == 0 (even number)
              new_str += l.upper() # add an upper cased letter to the new_str
          else: # if index number nth
              new_str += l # add the other letters to new_str as they are
      return new_str # returns the string new_str
      

      【讨论】:

        【解决方案5】:

        一个简化的答案是:

            def make_nth_letter_capital(word, n):
                return word[:n].capitalize() + word[n:].capitalize()
        

        【讨论】:

        • 您能否添加简短说明此代码的作用
        【解决方案6】:
        def capitalize_n(string, n):
        return string[:n] + string[n].capitalize() + string[n+1:]
        

        这很完美

        【讨论】:

          【解决方案7】:

          你可以使用:

          def capitalize_nth(text, pos):
              before_nth = text[:pos]
              n = text[pos].upper()
              new_pos = pos+1
              after_nth = text[new_pos:]
              word = before_nth + n + after_nth
              print(word)
          
          capitalize_nth('McDonalds', 6)
          

          结果是:

          'McDonaLds'
          

          我认为这是所有答案中最简单的...

          【讨论】:

            猜你喜欢
            • 2022-01-09
            • 1970-01-01
            • 1970-01-01
            • 2017-03-20
            • 2018-01-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多