Python string Slicing

Source: Internet
Author: User
This article mainly introduces the information about the string slicing operation in Python. For more information, see I. number of characters in the string

Print "Hello" [0] indicates the first character in the output string
Print "Hello" [-1] indicates the last character in the output string

Ii. string segmentation

Print "Hello" [1: 3]

# The first parameter indicates the following table in the original string
# The second description indicates the subscript of the first character of the remaining string after segmentation in the original string

This sentence is a bit wordy. Let's look at the output result directly:

El

Iii. Special situations

(1) print "Hello" [: 3] starting from the first character

(2) print "Hello" [0:] is truncated starting from the first character until the last character.

(3) print "Hello" [:] Same principle (2)

View output results:

El
Hello
Hello

4. Step Size Truncation

Print "Hello" [: 2]

Print "Hello" [:-2]

It indicates that the string is truncated from the first character, and the interval is 2 characters.

Output result:

Hlo

OlH

Python slice strings

Slice string

The string 'xxx' and the Unicode string u'xxx' can also be considered as a list. Each element is a character. Therefore, the string can also be sliced, but the operation result is still a string:

>>> 'Abcdef' [: 3]
'Abc'
>>> 'Abcdef' [-3:]
'Efg'
>>> 'Abcdef' [: 2]
'Aceg'

In many programming languages, many types of truncation functions are provided for strings. The purpose is to slice strings. Python does not have a function to intercept strings. You only need to slice an operation to complete the process, which is very simple.

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.