Python string processing examples
2021/05/04 categories:Python| tags:Python|
Access to characters
String index
h | e | l | l | o | w | o | r | l | d | ! | ! | ! | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
-14 | -13 | -12 | -11 | -10 | -9 | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
Code
a = 'hello world!!!'
print(a[0])
print(a[1])
print(a[-1])
print(a[-5])
print(a[1:4])
print(a[-5:-3])
print(a[:4])
print(a[-5:])
Result
h
e
!
l
ell
ld
hell
ld!!!
Create
Substitute normally
Code
a = 'hello world!!!'
print(a)
Result
hello world!!!
Repeat with operator *
Code
a = 'hello' * 3
print(a)
Result
hellohellohello
Combine
Join with operator +
Code
a = 'hello'
b = 'world!!!'
c = a + b
print(c)
Result
helloworld!!!
Join list with join
Code
a = 'hello'
b = 'world!!!'
c = ' '.join([a, b])
print(c)
Result
hello world!!!
Split
Split every 2 characters (regular expression)
Code
import re
a = 'abcdefghijk'
b = re.split('(..)',a)[1::2]
print(b)
Result
['ab', 'cd', 'ef', 'gh', 'ij']
Divided every 2 characters (list comprehension)
Code
a = 'abcdefghijk'
b = [ a[i: i+2] for i in range(0, len(a), 2) ]
print(b)
Result
['ab', 'cd', 'ef', 'gh', 'ij', 'k']
Search
Search for the position of a specific character
Code
a = 'abcabcabcabcabcabcabc'
b = a.index('c')
print(b)
Result
2
Get all the positions of a specific character
Code
a = 'abcabcabcabcabcabcabc'
b = [ n for n, s in enumerate(a) if s == 'c' ]
print(b)
Result
[2, 5, 8, 11, 14, 17, 20]
Get the most characters
Code
a = 'abcdddddefffg'
b = max( set(a), key=a.count )
print(b)
Result
d
Sorting
Reverse the strings
Code
a = 'abcdefg'
b = a[::-1]
print(b)
Result
gfedcba
Get
Get a string by skipping one character
Code
a = 'a_b_c_d_e_f_g'
b = a[::2]
print(b)
Result
abcdefg
conversion
Convert a string of numbers to a number
Code
a = '334'
b = int(a)
print(b, type(b))
Result
334 <class 'int'>
Convert strings to ASCII code
Code
a = '123abcABC'
b = [ ord(c) for c in a ]
print(b)
Result
[49, 50, 51, 97, 98, 99, 65, 66, 67]
Convert a string to a byte string and convert it to a list
Code
a = '123abcABC'
b = a.encode()
c = [c for c in b]
print(b)
print(c)
Result
b'123abcABC'
[49, 50, 51, 97, 98, 99, 65, 66, 67]
Convert string to byte string
Code
a = '123xyzXYZ'
b = a.encode()
c = b.hex()
print(b, type(b))
print(c, type(c))
Result
b'123xyzXYZ' <class 'bytes'>
31323378797a58595a <class 'str'>