Common operating skills in Python strings summary

This article summarizes the common examples of operating skills in Python strings. Share to you for your reference, as follows:

Reverse a string

>>> S = 'abcdefghijklmnop'
>>> S[::-1]
'ponmlkjihgfedcba'

This usage is called three-limit slices

In addition, the object slice can also be used, e.g.

>>> 'spam'[slice(None, None, -1)]
>>>

Conversion between unicode character code (single-character strings)

>>> ord('s') # ord -> ordinal
115
>>> chr(115) # chr -> char?
's'

Binary Coded Decimal

>>> B = '1101'
>>> I = 0
>>> while B != '':
...   I = I * 2 + (ord(B[0]) - ord('0'))
...   B = B[1:]
...
>>> I
13

Binary to decimal calculation here is that we have become accustomed to the calculation methods are not the same, we are generally accustomed to every binary multiplied by the weight and then summed.

The calculation here is actually similar with left shift, calculate the direction from left to right.

(1)2 = 1
(11)2 = (1)2 << 1 + 1
(110)2 = (11)2 << 1 + 0
(1101)2 = (110)2 << 1 + 1

Of course, there's an easier way

>>> int('1101', 2)
13
>>> bin(13)
'0b1101'

Add a break character for each character

>>> S = 'spammy'
>>> L = list(S)
>>> L
['s', 'p', 'a', 'm', 'm', 'y']
>>> L[3] = 'x'
>>> L[4] = 'x'
>>> L
['s', 'p', 'a', 'x', 'x', 'y']
>>> S = '-'.join(L)
>>> S
's-p-a-x-x-y'
>>>

More concise version

>>> 'SPAM'.join(['eggs', 'sausage', 'ham', 'toast'])
'eggsSPAMsausageSPAMhamSPAMtoast'

I write to you, for everyone to recommend a very wide python learning resource gathering, click to enter , there is a senior programmer before learning to share

Experience, study notes, there is a chance of business experience, and for everyone to carefully organize a python to combat zero-based item of information,

Python day to you on the latest technology, prospects, learning to leave a message of small details

Released five original articles · won praise 0 · Views 904

Guess you like

Origin blog.csdn.net/haoxun10/article/details/104663286