Shashank Sahu
Shashank Sahu

Reputation: 31

How to apply different operation on the odd and even words of the string?

I am trying to update my string such that:

For example, if my input string is:

n = 'what is the boarding time in bangalore station'

I want my output string to be:

WHAT si THE gnidraob TIME ni BANGALORE noitats

Here's the code I tried:

n = 'what is the boarding time in bangalore station'
m = n.split(" ")
k=m[0::2]
for i in k:
    print(i.upper())

Upvotes: 1

Views: 2390

Answers (7)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48090

You may use zip with the list comprehension expression (along with str.join) to get the desired string. For example:

>>> my_str = "what is the boarding time in bangalore station"
>>> words = my_str.split()  # list of words

>>> ' '.join(['%s %s'%(x.upper(), y[::-1]) for x, y in zip(words[::2], words[1::2])])
'WHAT si THE gnidraob TIME ni BANGALORE noitats'

Note: Here I am using list comprehension instead of generator expression because though generator expressions are more efficient but that is not the case when used with str.join. In order to know the reason for this weird behavior, please take a look at:

Most of the comprehension based answers here are using generator though they are referring it as list comprehension :D :D

Upvotes: 5

alvas
alvas

Reputation: 122188

How about:

n = 'what is the boarding time in bangalore station'

' '.join([token.upper() if i%2==0 else token[::-1] 
          for i, token in enumerate(n.split())
         ]
        )
  1. Iterate with enumerate() to keep a count.
  2. Check the odd vs even with i%2
  3. Uppercase if even, reverse string (i.e. str[::-1]) if odd
  4. Join the list of substrings with ' '.join([...])

Upvotes: 0

DARK_C0D3R
DARK_C0D3R

Reputation: 2257

taking not to high level, just by if-else:

n = 'what is the boarding time in bangalore station'
m = list(n.split(' '))
for i in range(len(m)):
    if i%2==0:
      print(m[i].upper(),end=' ')
    else:
        print(m[i][::-1].lower(),end=' ')

Upvotes: 1

Adem Öztaş
Adem Öztaş

Reputation: 21466

Another list comprehension solution:

n = 'what is the boarding time in bangalore station'
print(' '.join(word[::-1] if ind % 2 == 1 else word.upper() for ind, word in enumerate(n.split())))

Output:

'WHAT si THE gnidraob TIME ni BANGALORE noitats'

Another solution:

upper_words = [item.upper() for item in n.split()[0::2]]
reverse_words = [item[::-1] for item in n.split()[1::2]]
print(' '.join(word[0] + ' ' + word[1] for word in zip(upper_words, reverse_words)))

Output:

'WHAT si THE gnidraob TIME ni BANGALORE noitats'

Upvotes: 1

A little be more descriptive in one single line:

print(' '.join([w[::-1] if i % 2 else w.upper() for i, w in enumerate(n.split())]))

OUTPUT:

'WHAT si THE gnidraob TIME ni BANGALORE noitats'

Upvotes: 1

cs95
cs95

Reputation: 402872

Your solution is incomplete. Instead of slicing every alternate word and performing one kind of operation at a time, iterate over each one in turn, handling it as appropriate.

Here's one simple way of tackling your problem. Define a little function to do this for you.

  1. split the string into words
  2. for each word, check if it is an even word. If it is, then uppercase it. If not, reverse it
  3. join the transformed words into a single string

def f(n):
    for i, w in enumerate(n.split()):
        if i % 2 == 0:
            yield w.upper()    # uppercase even words
        else:
            yield w[::-1]      # reverse odd words

>>> ' '.join(f('what is the boarding time in bangalore station'))
'WHAT si THE gnidraob TIME ni BANGALORE noitats'

What f does is split the string into a list of words. enumerate transforms the list into a list of (index, word) tuples. Use the index to determine whether the word is an odd or even word. yield transforms the function into a generator, yielding one word at a time from the loop. Finally, str.join joins each word back into a single string.

Note that there are other ways to accomplish this. I leave them as an exercise to you.

Upvotes: 5

Chiheb Nexus
Chiheb Nexus

Reputation: 9267

Another way to answer your question using comprehension :

n = 'what is the boarding time in bangalore station'
b = n.split()
final = ' '.join(map(lambda x: ' '.join(x), ((k.upper(), v[::-1]) for k, v in zip(b[::2], b[1::2]))))

print(final)

Output:

'WHAT si THE gnidraob TIME ni BANGALORE noitats'

Upvotes: 0

Related Questions