Five methods for processing one character each time in Python, python5
Purpose
Each character of a string is processed. In fact, each character (Char) is a one-character string.
Method
1. Use the built-in function list ()
Copy codeThe Code is as follows:
>>> A_string = 'python'
>>> Char_list = list (A_string)
>>> Char_list
['P', 'y', 't', 'h', 'O', 'n']
2. Use the for statement to traverse strings
Copy codeThe Code is as follows:
>>> For c in A_string:
C. upper ()
'P'
'Y'
'T'
'H'
'O'
'N'
3. List Parsing
Copy codeThe Code is as follows:
>>> Char_list = [c. title () for c in A_string]
>>> Char_list
['P', 'y', 't', 'h', 'O', 'n']
4. map () function
Copy codeThe Code is as follows:
>>> Map (lambda c: c. lower (), A_string)
['P', 'y', 't', 'h', 'O', 'n']
5. Use set ()
Copy codeThe Code is as follows:
B _string = 'hello, world'
>>> Set (A_string). difference (set (B _string ))
Set (['y', 'h', 't', 'P', 'n'])