0

Go through the string below and if the length of a word is even change it to "even!"

Code: str1 = "Print every word in this sentence that has an even number of letters" for a in str1.split(): if len(a)%2 ==0: print('even!') else: print (a) #Desired output: ['Print', 'every', 'even!', 'even!', 'even!', 'even!, 'that', ... , 'even!']

15th Feb 2022, 4:31 AM
Jaz
Jaz - avatar
4 Answers
+ 4
You're missing parenthesis for split() method. Also, you can use ternary operator to do it like this str1 = "Print every word in this sentence that has an even number of letters" a = ["even!" if len(a)%2 == 0 else a for a in str1.split() ] print(a)
15th Feb 2022, 4:41 AM
Simba
Simba - avatar
+ 2
Simba thanksss 😊
15th Feb 2022, 4:45 AM
Jaz
Jaz - avatar
+ 1
You're welcome! I have just seen your updated question. In this context, you can declare an empty list and add it each items using append() instead.
15th Feb 2022, 4:49 AM
Simba
Simba - avatar