【发布时间】:2013-03-29 07:02:19
【问题描述】:
我试过这个:Capitalize a string。任何人都可以提供一个简单的脚本/sn-p 作为指南吗?
Python 文档有 capitalize() 函数,它使首字母大写。我想要make_nth_letter_cap(str, n)之类的东西。
【问题讨论】:
标签: python string capitalize
我试过这个:Capitalize a string。任何人都可以提供一个简单的脚本/sn-p 作为指南吗?
Python 文档有 capitalize() 函数,它使首字母大写。我想要make_nth_letter_cap(str, n)之类的东西。
【问题讨论】:
标签: python string capitalize
将第 n 个字符大写并将其余字符小写,如 capitalize() 所做的那样:
def capitalize_nth(s, n):
return s[:n].lower() + s[n:].capitalize()
【讨论】:
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:]])
【讨论】:
''.join([a, b, c]) 或a+b+c 哪个更有效(或者是否值得担心将几个字符串相对于代码库中的其他部分连接起来所花费的时间)。
x = "string"
y = x[:3] + x[3].swapcase() + x[4:]
输出
strIng
请记住,swapcase 将反转大小写,无论是小写还是大写。
我用这个只是为了展示另一种方式。
【讨论】:
我知道这是一个老话题,但这可能对将来的某人有用:
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'
我认为这是所有答案中最简单的...
【讨论】: