Python如何大写字符串的第n个字母

时间:2013-04-07 01:53:45

标签: python string capitalize

我试过了:Capitalize a string。任何人都可以为指南提供简单的脚本/片段吗?

Python文档具有capitalize()函数,这使得首字母大写。我想要make_nth_letter_cap(str, n)

之类的东西

7 个答案:

答案 0 :(得分:11)

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:]])

答案 1 :(得分:9)

将第{n}个字符大写,并将其余字母小写为capitalize()

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

答案 2 :(得分:0)

x = "string"
y = x[:3] + x[3].swapcase() + x[4:]  

输出

strIng  

Code

请注意,swapcase会反映案件是低级还是高级 我用它来表示另一种方式。

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

一个简单的答案是:

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

答案 5 :(得分:0)

http://localhost:8080/bma/api/v1

这是我发现运行正常的代码。它会检查字符串长度以避免错误。

答案 6 :(得分:0)

您可以使用:

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'

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

相关问题