A summary of how Python handles a fixed number of characters at a time _python

Source: Internet
Author: User

First of all, to see how a character can be processed each time, there are several ways to do it:
Method One:

Copy Code code as follows:

>>> a= ' 1234567 '
>>> List (a)
[' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ']
>>>

Method Two:
Copy Code code as follows:

>>> a= ' 1234567 '
>>> for I in a:
... print I
...
1
2
3
4
5
6
7
>>>

Method Three: List resolution (map)
Copy Code code as follows:

>>> A
' 1234567 '
>>> [Int (i) +1 for I in a]
[2, 3, 4, 5, 6, 7, 8]
>>>

But if you handle two characters or more characters at a time, the above method is not working, I summarize the following two kinds:

Method One: Use a fragment operation, processing two characters at a time:

Copy Code code as follows:

>>> a= ' Abcdefghijk '
>>> num=0
>>> while True:
... str = a[num:num+2]
. If str:
... print str
. else:
.. break
. num + + 2
...
Ab
Cd
Ef
Gh
Ij
K
>>>

Method Two: Use regular expression, split string, processing 3 characters at a time
Copy Code code as follows:

>>> Import re
>>> a= "1234567890"
>>> for I in Re.findall (". { 1,3} ", a):
... print I
...
123
456
789
0
>>>

You can change the n characters at a time, depending on your requirements.

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.