Python How to capitalize nth letter of a string

╄→尐↘猪︶ㄣ 提交于 2020-01-12 19:01:25

问题


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).


回答1:


Capitalize n-th character and lowercase the rest as capitalize() does:

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



回答2:


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:

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



回答3:


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

Output

strIng  

Code

Keep in mind that swapcase will invert the case whether it is lower or upper.
I used this just to show an alternate way.




回答4:


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



回答5:


A simplified answer would be:

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



回答6:


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.



来源:https://stackoverflow.com/questions/15858065/python-how-to-capitalize-nth-letter-of-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!