Home > Backend Development > Python Tutorial > Python中每次处理一个字符的5种方法

Python中每次处理一个字符的5种方法

WBOY
Release: 2016-06-06 11:17:27
Original
1210 people have browsed it

目的

对字符串的每个字符进行处理,其实每个字符(Char)就是一个长度为1的字符串。

方法

1.使用内建函数list()

代码如下:


>>> A_string='Python'
>>> char_list=list(A_string)
>>> char_list
['P', 'y', 't', 'h', 'o', 'n']

2.使用for语句对字符串进行遍历

代码如下:


>>> for c in A_string:
        c.upper()

'P'
'Y'
'T'
'H'
'O'
'N'


 

3.列表解析

代码如下:


>>> char_list=[c.title() for c in A_string]
>>> char_list
['P', 'Y', 'T', 'H', 'O', 'N']


 

4.map()函数

代码如下:


>>> map((lambda c:c.lower()),A_string)
['p', 'y', 't', 'h', 'o', 'n']


 

5.使用集合set()

代码如下:


B_string='Hello,World'
>>> set(A_string).difference(set(B_string))
set(['y', 'h', 't', 'P', 'n'])

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template