Home  >  Article  >  Backend Development  >  String indexing and sharding in Python

String indexing and sharding in Python

高洛峰
高洛峰Original
2016-10-19 16:14:421700browse

1. The index of the string

gives a string and can output any character. If the index is a negative number, it is equivalent to counting from back to front.

>>> str="HelloWorld!"

>>> print str[0]

H

>>> print str[-4]

r

>>> str="HelloWorld!"

>>> print str[0]

H

>>> print str[-4]

r

2. Slicing of strings

Slicing is to separate parts from a given string content.

>>> 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!

Extended form of sharding:

str[I,J,K] means from I to J-1, indexing every K elements , if K is a negative number, it is indexed from left to right.

>>> print str[2:7:2]

loo

>>> print str[2:7:1]

lloWo

>>> print str[2:7:2]

loo

>>> print str[2:7:1]

lloWo

ord function converts characters into corresponding ASCII code values, while chr function converts numbers into characters. For example:

>>> print ord('a')

97

>>> print chr(97)

a

>>>

>>> print ord('a')

97

>>> print chr(97)

a

>>>

Modifying a string in Python can only be reassigned.

Every time a string is modified, a new string object is generated, which seems to cause a decrease in efficiency. In fact, Python will automatically garbage collect strings that are no longer used, so

The object reuses space previously occupied by a string.


String formatting:

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

'1 goujinping 8 you!'

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

'1 goujinping 8 you!'


Statement:
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