string = "Hello world, my name is John"
string = string.split()
string_index = str(string[1::2])
print(string_index.upper())
I am trying to use the .split function to pull words from the string. It works and can pull every other word. For example here "WORLD, NAME, JOHN," and now I would like to use the .join function to then put the capitalized words back into the original string. Creating something like this; "hello WORLD, my NAME is JOHN".
It has to use the .split and .join functions. I know there are other ways of doing this.
Below is what I tried and of course failed. I was thinking that it may be joined back into the string somehow.
string_index.upper().join(string)
I expected it to simply join what I had changed and put it back into the original string. It did not and wasn't that simple.
CodePudding user response:
Use a list comprehension with enumerate
and a ternary expression checking the even/odd words with %2
(i%2
evaluates as 1
/True
if even, else 0
/False
), then join
:
out = ' '.join([s.upper() if i%2 else s for i,s in enumerate(string.split())])
Output: 'Hello WORLD, my NAME is JOHN'
CodePudding user response:
Enumerate over the split input string, use the index of a word and if it's divisible by 2 make it upper, otherwise take the non modified item Then just join them back together with space as the separator.
string = "Hello world, my name is John"
words = [word.upper() if idx%2==0 else word for idx, word in enumerate(string.split()]
modified_words = ' '.join(words)
CodePudding user response:
You can do this with list comprehension ternary expression:
string = "Hello world, my name is John"
words_list = string.split()
# Capitalize every other word
new_words_list = [word.upper() if i % 2 == 1 else word for i, word in enumerate(words_list)]
# Put the string back together
new_string = " ".join(new_words_list)