|
The Python Book
|
|
Following snap is taken from here: mkaz.blog/code/python-string-format-cookbook. Go there, there are more examples
Reverse the words in a string
Tactic:
- reverse the whole string
- reverse every word on its own
Code:
s="The goal is to make a thin circle of dough, with a raised edge."
r=' '.join([ w[::-1] for w in s[::-1].split(' ') ])
The notation s[::-1] is called extended slice syntax, and should be read as [start:end:step] with the start and end left off.
Note: you also have the reversed() function, which returns an iterator:
s='circumference'
''.join(reversed(s))
'ecnerefmucric'
| |