[英]Python How to capitalize nth letter of a string
我試過這個: 大寫字符串。 任何人都可以提供一個簡單的腳本/片段作為指導嗎?
Python 文檔有capitalize()
function 使首字母大寫。 我想要類似make_nth_letter_cap(str, n)
的東西。
大寫第 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 畫家的算法:
''.join([my_string[:n], my_string[n].upper(), my_string[n + 1:]])
這是綜合解決方案:輸入單個單詞、單行句子或多行句子,第n個字母將轉換為大寫字母,您將返回轉換后的字符串為output:
您可以使用以下代碼:
def nth_letter_uppercase(string,n):
listofwords = string.split()
sentence_upper = ''
for word in listofwords:
length = len(word)
if length > (n - 1):
new_word = word[:n-1] + word[n-1].upper() + word[n:]
else:
new_word = word
sentence_upper += ' ' + new_word
return sentence_upper
調用上面定義的 function (我想將每個單詞的第二個字母轉換為大寫字母):
string = '''nature is beautiful
and i love python'''
nth_letter_uppercase(string,2)
output 將是:
'nAture iS bEautiful aNd i lOve pYthon'
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'
我認為這是所有答案中最簡單的......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.