1

I am trying to update my string such that:

  • every word on the odd position becomes uppercase.
  • every word on the even position gets reversed

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())
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126

7 Answers7

5

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.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
cs95
  • 379,657
  • 97
  • 704
  • 746
5

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

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • 1
    `list comprehension` vs. `generator expression` with `str.join()` thing is very interesting. Not easy to discover. Thank you. Regarding the same, I've just read Raymond Hettinger's answer [here](https://stackoverflow.com/a/9061024/8709791). I'm wondering if it's the same with Python 3.x. – srikavineehari Jan 06 '18 at 19:26
  • @srig Yes, you'll see the same behavior in Python 3 as well. – Moinuddin Quadri Jan 06 '18 at 19:33
1

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'
Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42
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'
1

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=' ')
DARK_C0D3R
  • 2,075
  • 16
  • 21
0

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'
Chiheb Nexus
  • 9,104
  • 4
  • 30
  • 43
0

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([...])
alvas
  • 115,346
  • 109
  • 446
  • 738