Python string indexing and sharding

Source: Internet
Author: User

1. String Index

Returns a string that can be any character. If the index is negative, it is equivalent to the number from the back to the front.

[Python]
>>> Str = "HelloWorld! "
>>> Print str [0]
H
>>> Print str [-4]
R

>>> Str = "HelloWorld! "
>>> Print str [0]
H
>>> Print str [-4]
R
2. String sharding

Fragment is to extract part of the content from a given string.

[Python]
>>> Str = "HelloWorld! "
>>> Print str [0]
H
>>> Print str [-4]
R
>>> Print str [1: 4]
Ell
>>> Print str [:-7]
Hell
>>> Print str [5:]
World!

>>> Str = "HelloWorld! "
>>> Print str [0]
H
>>> Print str [-4]
R
>>> Print str [1: 4]
Ell
>>> Print str [:-7]
Hell
>>> Print str [5:]
World!
Shard extension form:

Str [I, J, K] means to index every K elements from I to J-1. If K is negative, it is indexed from left to left.

[Python]
>>> Print str []
Loo
>>> Print str []
LloWo

>>> Print str []
Loo
>>> Print str []
LloWo
The ord function converts a character to the corresponding ASCII value, while the chr function converts a number to a character. For example:

[Python]
>>> Print ord ('A ')
97
>>> Print chr (97)
A
>>>

>>> Print ord ('A ')
97
>>> Print chr (97)
A
>>>

In Python, you can only change the value of a string.

Each time a string is modified, a New String object is generated, which seems to cause a reduction in efficiency. In fact, Python automatically recycles strings that are no longer used.

The new object reuses the space of the previous string.

 

String formatting:

[Python]
>>> "% D % s % d you! "% (1," goujinping ", 8)
'1 goujinping 8 you! '

>>> "% D % s % d you! "% (1," goujinping ", 8)
'1 goujinping 8 you! '

 

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.