簡體   English   中英

如何在字符串中大寫帶有奇數索引的字符?

[英]How can I capitalize a character with an odd-numbered index in a string?

因此,當我遇到奇數索引中的大寫字符時,便是在進行練習。 我嘗試了這個:

for i in word:
   if i % 2 != 0:
       word[i] = word[i].capitalize()
   else:
       word[i] = word[i]

但是,最終顯示錯誤,提示並非所有字符串都可以轉換。 您能幫我調試此代碼段嗎?

問題是python中的字符串是不可變的,您不能更改單個字符。 此外,當您遍歷字符串時,遍歷字符而不是索引 因此,您需要使用其他方法

解決方法是

  • (使用enumerate

     for i,v in enumerate(word): if i % 2 != 0: word2+= v.upper() # Can be word2+=v.capitalize() in your case # only as your text is only one character long. else: word2+= v 
  • 使用清單

     wordlist = list(word) for i,v in enumerate(wordlist): if i % 2 != 0: wordlist[i]= v.upper() # Can be wordlist[i]=v.capitalize() in your case # only as your text is only one character long. word2 = "".join(wordlist) 

關於capitalizeupper簡短注釋。

從文檔中capitalize

返回字符串的副本,該字符串的首個字符大寫 ,其余小寫。

因此,您需要使用upper來代替。

返回字符串的副本,其中所有大小寫的字符都轉換為大寫。

但是在您的情況下,兩者都能正常工作。 或者,正如帕德里克所說跨越 “有在這個例子中的效率和輸出幾乎沒有差別明智”

您需要枚舉任何大小寫為i字符,其中i是單詞中每個字符的索引:

word = "foobar"

print("".join( ch.upper() if i % 2 else ch for i, ch in enumerate(word)))
fOoBaR

ch.upper() if i % 2 else ch是一個條件表達式 ,如果條件為True,則我們更改char,否則保留原樣。

i是字符串中的實際字符時,您不能i % 2 ,您將需要在代碼中使用范圍或使用枚舉並將更改后的字符連接到輸出字符串或將單詞設為列表。

使用列表,您可以使用分配:

word = "foobar"
word = list(word)
for i, ele in enumerate(word):
   if i % 2:
       word[i] = ele.upper()

print("".join(word))

使用輸出字符串:

word = "foobar"
out = ""
for i, ele in enumerate(word):
    if i % 2:
        out += ele.upper()
    else:
        out += ele

if i % 2:if i % 2 != 0

這就是我將單詞或句子中的單詞字母更改為大寫的方式

word = "tester"

letter_count = 1
new_word = []
for ch in word:
    if not letter_count % 2 == 0:
        new_word.append(ch.upper())
    else:
        new_word.append(ch)
    letter_count += 1

print "".join(new_word)

如果我想將句子中的奇數詞改為大寫,我會這樣做

sentence = "this is a how we change odd words to uppercase"

sentence_count = 1
new_sentence = []
for word in sentence.split():
    if not sentence_count % 2 == 0:
        new_sentence.append(word.title() + " ")
    else:
        new_sentence.append(word + " ")
    sentence_count += 1

print "".join(new_sentence)

我認為這會有所幫助...

s = input("enter a string : ")
for i in range(0,len(s)):
    if(i%2!=0):
        s = s.replace(s[i],s[i].upper())  
print(s)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM