Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

python text Strings are reversed character by character and word by word


May 10, 2021 Python2


Table of contents


python text Strings are reversed character by character and word by word

Scene:

Strings are reversed character by character and word by word

Let's start with the character-by-character inverse of strings, and since python provides a very useful slice, you only need one sentence to do it

  >>> a='abc edf degd'  
  >>> a[::-1]  
  'dged fde cba'  
  >>>   

Then we'll look at the word inverse

1. We can also use slices

  >>> a='abc edf degd'  
  >>> a.split ()[::-1]  
  ['degd''edf''abc']  

2. You can use the native method reverse

  >>> a='abc edf degd'  
  >>> result=a.split()  
  >>> result  
  ['abc''edf''degd']  
  >>> result.reverse()  
  >>> result  
  ['degd''edf''abc']  
  >>> result=' '.join (result)  
  >>> result  
  'degd edf abc'  
  >>>   

During the inverse, I was surprised to find another way to use join

  >>> a='abcd'  
  >>> ' '.join (a)  
  'a b c d'  
  >>> a='abc edf degd'  
  >>> ' '.join (a)  
  'a b c   e d f   d e g d'  
  >>>   

It can quickly add our assigned characters to the middle of each character

  >>> '+'.join (a)  
  'a+b+c+ +e+d+f+ +d+e+g+d'  
  >>>   

In summary, or the best way to use seing, the most recommended use