This article mainly introduces 5 methods of each character in Python, that is, to split the string into a character array or to cut the string into individual characters, a friend can refer to the
Objective
Each character of a string is processed, in fact, each character (Char) is a string of length 1.
Method
1. Use the built-in function list ()
The code is as follows:
>>> a_string= ' Python '
>>> char_list=list (a_string)
>>> char_list
[' P ', ' y ', ' t ', ' h ', ' o ', ' n ']
2. Use a For statement to traverse a string
The code is as follows:
>>> for C in a_string:
C.upper ()
P
Y
T
H
O
N
3. List resolution
The code is as follows:
>>> Char_list=[c.title () for C in a_string]
>>> char_list
[' P ', ' Y ', ' T ', ' H ', ' O ', ' N ']
4.map () function
The code is as follows:
>>> map ((Lambda C:c.lower ()), a_string)
[' P ', ' y ', ' t ', ' h ', ' o ', ' n ']
5. Use Set Set ()
The code is as follows:
b_string= ' Hello,world '
>>> set (a_string). Difference (set (b_string))
Set [' Y ', ' h ', ' t ', ' P ', ' n ']