It is well known that the string in Python cannot be changed, and the inverse of a string naturally creates a copy; The simple method of mouth is, of course, a slice of "-1" in step:
result = Astring[::-1]
If you invert by word, you need three steps: string---> Word list, reverse list, word list---> string;
1 result = astring.split ()2result.reverse () 3" . Join (Result)
If you prefer a concise and compact line of code, you can do this:result = '. Join (Astring.split () [:: -1])
But [::-1] reduces readability, but it can also be written like this:result = '. Join (Reversed (Astring.split ()))
Suppose the case: while working with the string, it is guaranteed not to change the number of spaces, and it is obvious that the above method does not work, which is when the regular expression comes out:
1 Import Re 2 result = Re.split (r'(\s+)', astring)3result.reverse () 4'. Join (Result) # Note ' There's no space in the middle ' Oh
The same line can accomplish this task:result = '. Join (Re.split (R ' (\s+) ', astring) [:: -1])
summary: Unfortunately, this article at the beginning of the writing is better than this, but because of the accidental loss of unfinished draft, but the inspiration is not all, Do your best to write it like this;