Python implements an example of string inversion output

  • 2020-06-07 04:45:18
  • OfStack

This article is an example of Python's implementation of string inversion output. To share for your reference, specific as follows:

1. Sometimes we might want to output strings in reverse order. Here are a few ways to do this

Method 1: By indexing method


>>> strA = "abcdegfgijlk"
>>> strA[::-1]
'kljigfgedcba'

Method 2: Flip the group list


#coding=utf-8
strA = raw_input(" Please enter the string you want to flip: ")
order = []
for i in strA:
 order.append(i)
order.reverse()  # Invert the list 
print ''.join(order)  # will list Convert to a string 

Execution Results:


 Please enter the string you want to flip: abcdeggsdd
ddsggedcba

2. Output characters with odd and even coordinates in the string respectively

The easiest way to do this is by slicing a sequence.


>>> str_a = "1a2b3c4d5e6f"
*** Output odd-numbered characters ***
>>> for i in str_a[::2]:
...  print i,
...
1 2 3 4 5 6
*** Output an even-digit character ***
>>> for j in str_a[1::2]:
...  print j,
...
a b c d e f

Of course, we could also use the following method, but this method is more troublesome.


#coding=utf-8
def oddEven(strA):
 odd = []
 even = []
 for i in range(len(strA)):
  if i % 2 == 0:
   even.append(strA[i])
  else :
   odd.append(strA[i])
 print " Even term: ", ''.join(even)
 print " An odd number of items: ", ''.join(odd)
strA = "1a2b3c4d5e6f7g8h9j"
print " Original string: ", strA
oddEven(strA)

Execution Results:


 Original string:  1a2b3c4d5e6f7g8h9j
 Even term:  123456789
 An odd number of items:  abcdefghj

It is worth noting that:

In our normal programming process, 1 must avoid the direct use of programming language keywords as variable names, especially Python language almost all objects can be assigned, if the system environment to the variable assignment often cause many strange problems, 1 must develop good programming habits.

The most typical one is the error of the isinstance() function. The code is correct, but it will give an error, indicating that str must have been assigned to the variable before this code.


>>> a = '123'
>>> isinstance(a, str)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types

For more information about Python, please refer to Python String Manipulation Skills summary, Python Coding skills Summary, Python Data Structure and Algorithm Tutorial, Python Functions Summary and Python Introduction and Advanced Classic Tutorial.

I hope this article has been helpful in Python programming.


Related articles: