繁体   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