Reputation: 23
Ask for a string from the user and make each alternative word lower and upper case (e.g. the string “I am learning to code” would become “i AM learning TO code”). Using the split and join functions will help you here.
I did a similar thing for characters in the string, but as I found out it doesn't work with full words.
new_string = input("Please enter a string: ")
char_storage = "" #blank string to store all the string's characters
char = 1
for i in new_string:
if char % 2 == 0:
char_storage += i.lower()
else:
char_storage += i.upper()
char += 1
print(char_storage)
I am still quite confused about how python connects char with new_string value, if anyone has a good website where it is explained I would be very grateful.
Upvotes: 0
Views: 1670
Reputation: 107
The shortest answer I can come up with would be:
new_string = input("Please enter a string: ").split()
char_storage = " ".join([x.upper() if i % 2 else x.lower() for i, x in enumerate(new_string)])
print(char_storage)
With " ".join()
you can concatenate every word in a list by a space. The argument creates a list of words in the input phrase and switches characters to upper if the modulo is not 0.
Upvotes: 0
Reputation: 191728
You need to loop over words, not characters of a string, so split your input into words, ex. on whitespace
new_string = input("Please enter a string: ").split()
The Python official documentation tells you that strings are iterable objects. Iterating them gives you characters.
I'd recommend separating code into functions and using str.join
def change_case(x, upper):
return x.upper() if upper else x.lower()
char_storage = ' '.join(change_case(x, i%2!=0) for i, x in enumerate(new_string))
Upvotes: 0
Reputation: 419
You can try this
new_string = input("Please enter a string: ")
char_storage = "" #blank string to store all the string's characters
char = 1
for i in new_string.split():
if char != 1:
char_storage += " "
if char % 2 == 0:
char_storage += i.lower()
else:
char_storage += i.upper()
char += 1
Upvotes: 1