python - How can I capitalize a character with an odd-numbered index in a string? -
so doing our exercise when came across capitalizing characters in odd indices. tried this:
for in word: if % 2 != 0: word[i] = word[i].capitalize() else: word[i] = word[i]
however, ends showing error saying not strings can converted. can me debug code snippet?
the problem strings in python immutable , cannot change individual characters. apart fro when iterate through string iterate on characters , not indices. need use different approach
a work around is
(using
enumerate
)for i,v in enumerate(word): if % 2 != 0: word2+= v.upper() # can word2+=v.capitalize() in case # text 1 character long. else: word2+= v
using lists
wordlist = list(word) i,v in enumerate(wordlist): if % 2 != 0: wordlist[i]= v.upper() # can wordlist[i]=v.capitalize() in case # text 1 character long. word2 = "".join(wordlist)
a short note on capitalize
, upper
.
from docs capitalize
return copy of string first character capitalized , rest lowercased.
so need use upper
instead.
return copy of string all cased characters converted uppercase.
but in case both work accurately. or padraic puts across "there pretty no difference in example efficiency or output wise"
Comments
Post a Comment