Python如何将字符串的第n个字母大写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15858065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python How to capitalize nth letter of a string
提问by Trojosh
I tried this: Capitalize a string. Can anybody provide a simple script/snippet for guideline?
我试过这个:大写一个字符串。任何人都可以提供一个简单的脚本/代码片段作为指南吗?
Python documentation has capitalize()function which makes first letter capital. I want something like make_nth_letter_cap(str, n).
Python 文档具有capitalize()使首字母大写的功能。我想要类似的东西make_nth_letter_cap(str, n)。
采纳答案by jfs
Capitalize n-th character and lowercase the rest as capitalize()does:
大写第 n 个字符并将其余字符小写,如下所示capitalize():
def capitalize_nth(s, n):
return s[:n].lower() + s[n:].capitalize()
回答by icktoofay
my_string[:n] + my_string[n].upper() + my_string[n + 1:]
Or a more efficient version that isn't a Schlemiel the Painter's algorithm:
或者更有效的版本不是Schlemiel 画家的算法:
''.join([my_string[:n], my_string[n].upper(), my_string[n + 1:]])
回答by cppcoder
回答by ZiP
I know it's an old topic but this might be useful to someone in the future:
我知道这是一个古老的话题,但这可能对将来的某人有用:
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
回答by roopali k
A simplified answer would be:
一个简化的答案是:
def make_nth_letter_capital(word, n):
return word[:n].capitalize() + word[n:].capitalize()
回答by gokulrejithkumar
def capitalize_n(string, n):
if len(string) > n:
return string[:n] + string[n:].capitalize()
else:
return 'String is short for the selected value of n!'
Here is the code that I found out to be working perfectly. It checks for the string length to avoid errors.
这是我发现运行良好的代码。它检查字符串长度以避免错误。

