5 ways to handle one character at a time in Python

Source: Internet
Author: User
Tags set set in python

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 ']

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.