0

Here goes my trivial Python code:

from re import match
str = "Hello"
print str[::-1]   # elloH
obj = match(r'(\w)(\w)(\w)(\w)(\w)', str)
for i in range(len(str)-1, -1, -1):  # or   reversed(range(len(str)))
    print obj.groups()[i],   # o l l e H

I have two queries in this code:

  1. What is the logic behind the range option in the list str[::-1] ? Because str[len(str):-1:-1] gives empty output and str[len(str):0:-1] gives output ``olle` and so on.
  2. How to make this regular expression r'(\w)(\w)(\w)(\w)(\w)' so compact? (i.e) removing the repeating or recursive redundant (\w), something like r'(\w)+'?
Ibrahim Quraish
  • 3,889
  • 2
  • 31
  • 39

3 Answers3

1

a) Please check the following code:

>>> str = "Hello"
>>> str[:]
'Hello'
>>> str[::1]
'Hello'
>>> str[::2]
'Hlo'
>>> str[::3]
'Hl'
>>> str[::-1]
'olleH'
>>> str[::-2]
'olH'
>>> str[-1]
'o'
>>>

From this we can reason that, the last number (n) in the [::n] indicates how many steps to jump from beginning. And if it's positive, it starts from position 0, if it's negative, it starts from the last position (which is -1).

Tamim Shahriar
  • 739
  • 4
  • 9
1
        import re
        str = "Hello"
        print str[::-1]   # elloH
        obj = re.findall(r"(\w)", str)
        for i in range(len(str)-1, -1, -1):  # or   reversed(range(len(str)))
            print obj.groups()[i]

This is what you are looking for.

vks
  • 67,027
  • 10
  • 91
  • 124
0
word = "Hello"
rword = " ".join(reversed(word))

'o l l e H'
Mauro Baraldi
  • 6,346
  • 2
  • 32
  • 43