Python text string-by-character inversion and word-wise reversal

Source: Internet
Author: User

python text string-by- character reversal and word-wise reversal

Scene:

String-by-character reversal and word-wise reversal

first, the string is reversed by character-by-word, python provides a very useful slice, so you just need a sentence to get it done.


  >>>a=' abc EDF DEGD '
  >>>a[::-1]
  ' dged fde CBA '
  >>>

And then we look at the word reversal.

1. Similarly, we can also use slices

  >>>a=' abc EDF DEGD '
  >>>a.split () [::-1]
  [' Degd ', ' EDF ', ' abc '] 

2. native methods can be used 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 '
  >>>

in the process of inversion, I accidentally found Join another way to use

  >>>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 re-add each character to the middle of our assigned character.

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

All in all, or use the method of slicing the best, the most recommended to use

Python text string-by-character inversion and word-wise reversal

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.