12

私はこれを試しました: Capitalize a string . ガイドライン用の簡単なスクリプト/スニペットを提供できる人はいますか?

Python のドキュメントにはcapitalize()、最初の文字を大文字にする関数があります。のようなものが欲しいmake_nth_letter_cap(str, n)

4

7 に答える 7

21

次のように、n 番目の文字を大文字にし、残りを小文字にcapitalize()します。

def capitalize_nth(s, n):
    return s[:n].lower() + s[n:].capitalize()
于 2013-04-07T02:22:11.897 に答える
14
my_string[:n] + my_string[n].upper() + my_string[n + 1:]

または、画家のシュレミエルのアルゴリズムではない、より効率的なバージョン:

''.join([my_string[:n], my_string[n].upper(), my_string[n + 1:]])
于 2013-04-07T01:56:19.250 に答える
0
def capitalize_n(string, n):
return string[:n] + string[n].capitalize() + string[n+1:]

これは完璧に機能します

于 2019-08-01T13:27:06.633 に答える
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
于 2018-08-29T18:53:04.010 に答える
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'

これは、そこにあるすべての答えの中で最も簡単だと思います...

于 2020-09-14T13:33:57.833 に答える