Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/facebook/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python如何大写字符串的第n个字母_Python_String_Capitalize - Fatal编程技术网

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

Python如何大写字符串的第n个字母,python,string,capitalize,Python,String,Capitalize,我试过这个:。有人能为指南提供一个简单的脚本/代码段吗 Python文档具有使首字母大写的函数。我想要类似于制作第n个字母\u cap(str,n)的东西 或者更高效的版本,而不是: 输出 strIng 请记住,swapcase将反转大小写,无论大小写是低还是高。 我使用它只是为了显示另一种方式。将第n个字符大写,其余字符小写,如下所示: 我知道这是一个老话题,但这可能对将来的人有用: def myfunc(str, nth): new_str = '' #empty string to

我试过这个:。有人能为指南提供一个简单的脚本/代码段吗

Python文档具有使首字母大写的函数。我想要类似于
制作第n个字母\u cap(str,n)
的东西

或者更高效的版本,而不是:

输出

strIng  

请记住,
swapcase
将反转大小写,无论大小写是低还是高。

我使用它只是为了显示另一种方式。

将第n个字符大写,其余字符小写,如下所示:


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

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

一个简单的答案是:

    def make_nth_letter_capital(word, n):
        return word[:n].capitalize() + word[n:].capitalize()
这个很好用

您可以使用:

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'

我认为这是所有答案中最简单的一个…

我在我的答案下面添加了一个注释这里有一些关于python中字符串连接的更多信息,在N=3的情况下,因此我们无法确定什么实现O(N)或O(N*N)更“有效”(对于如此小的N)。我不知道什么是更有效的
”。join([a,b,c])
a+b+c
(或者甚至值得担心与代码库中的其他部分相关联的两个字符串所需的时间)。您能简单解释一下这段代码的作用吗
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
    def make_nth_letter_capital(word, n):
        return word[:n].capitalize() + word[n:].capitalize()
def capitalize_n(string, n):
return string[:n] + string[n].capitalize() + string[n+1:]
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'