'print a string with alternating letters capitalized. IndexError string index out of range
This code creates a IndexError that shows that i is out of range.
string = "Hello World"
string_empty = ""
length = len(string)
for i in range(0, length):
string_empty += string[i]
if i <= length:
string_empty += string[i+1].upper()
print(f"alternate word capitalized: {string_empty}")
Solution 1:[1]
Why are you using indexes? You can just go through the characters themselves.
# 1 paragraph lorem ipsum from https://vlad-saling.github.io/star-trek-ipsum/
string = "We're acquainted with the wormhole phenomenon, but this... Is a remarkable piece of bio-electronic engineering by which I see much of the EM spectrum ranging from heat and infrared through radio waves, et cetera, and forgive me if I've said and listened to this a thousand times. This planet's interior heat provides an abundance of geothermal energy. We need to neutralize the homing signal."
def cap_letters(input_string: str) -> str:
result = ""
capitalize = True
for c in input_string.lower():
if capitalize:
result += c.upper()
else:
result += c
# only switch capitalization if it's a letter
if c.isalpha():
capitalize = not (capitalize)
return result
print(f"alternate letter capitalized:\n{cap_letters(string)}\n")
output:
alternate letter capitalized:
We'Re AcQuAiNtEd WiTh ThE wOrMhOlE pHeNoMeNoN, bUt ThIs... Is A rEmArKaBlE pIeCe Of BiO-eLeCtRoNiC eNgInEeRiNg By WhIcH i SeE mUcH oF tHe Em SpEcTrUm RaNgInG fRoM hEaT aNd InFrArEd ThRoUgH rAdIo WaVeS, eT cEtErA, aNd FoRgIvE mE iF i'Ve SaId AnD lIsTeNeD tO tHiS a ThOuSaNd TiMeS. tHiS pLaNeT's InTeRiOr HeAt PrOvIdEs An AbUnDaNcE oF gEoThErMaL eNeRgY. wE nEeD tO nEuTrAlIzE tHe HoMiNg SiGnAl.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
