I'm trying to make it so that my text alternates between upper and lower case like the question ask. It seems to skip 3 in the indexing and I can't figure out why.
sentence = input("Write a sentence")
newList = []
for i in range(len(sentence)):
if sentence[i] != " ":
newList.append(sentence[i])
listJoint = "".join(newList)
newList2 = []
for i in range(len(listJoint)):
if (listJoint.index(listJoint[i]) % 2) == 0:
print(listJoint.index(listJoint[i]))
newList2.append(listJoint[i].upper())
elif (listJoint.index(listJoint[i]) % 2) != 0:
print(listJoint.index(listJoint[i]))
newList2.append(listJoint[i].lower())
print(newList2)
#newListJoint = "".join(newList2)
#print(newListJoint[::-1])
Thanks in advance List index doesn't go 0 1 2 3 4
CodePudding user response:
The function .index() finds the first occurrence of that letter. 'L' occurs at index 2 and 3 so it would return 2 for both L's.
CodePudding user response:
Iterate through each character of the string and alternate upper/lower methods.
sentence = "Hello"
alternated_sentence = ''
for i, char in enumerate(sentence):
if i % 2:
alternated_sentence = char.upper()
else:
alternated_sentence = char.lower()
print(alternated_sentence)
#hElLo
CodePudding user response:
sentence = input("Write a sentence:")
# Remove spaces (as per your question)
sentence = sentence.replace(' ', '')
# Reverse the string order (as per your question)
sentence = sentence[::-1]
result = []
for i in range(len(sentence)):
if(i%2==1):
result.append(sentence[i].lower())
else:
result.append(sentence[i].upper())
print(''.join(result))
Here's the solution. The above code would give output as follows:
Write a sentence: Hello world
DlRoWoLlEh
CodePudding user response:
Thanks to everyone for the responses, I never realised index method referenced the first instance of the character. I have it working now:
sentence = input("Write a sentence")
newList = []
for i in range(len(sentence)):
if sentence[i] != " ":
newList.append(sentence[i])
listJoint = "".join(newList)
newList2 = []
for i, value in enumerate(newList):
if i % 2 == 0:
newList2.append(listJoint[i].upper())
elif i % 2 !=0:
newList2.append(listJoint[i].lower())
newListJoint = "".join(newList2)
print(newListJoint[::-1])