Python 简明教程

Python Slicing Strings

Python String slicing 是从给定字符串创建子字符串的方法。在此过程中,我们提取字符串的一部分或片段。通常,我们使用切片运算符 "[ : ]" 对 Python 字符串执行切片。在继续进行字符串切片之前,让我们了解一下字符串索引。

Python String slicing is a way of creating a sub-string from a given string. In this process, we extract a portion or piece of a string. Usually, we use the slice operator "[ : ]" to perform slicing on a Python String. Before proceeding with string slicing let’s understand string indexing.

在 Python 中, stringUnicode characters 的有序序列。字符串中的每个字符在序列中都有一个唯一索引。索引从 0 开始。字符串中的第一个字符的位置索引为 0。索引会一直递增到字符串末尾。

In Python, a string is an ordered sequence of Unicode characters. Each character in the string has a unique index in the sequence. The index starts with 0. First character in the string has its positional index 0. The index keeps incrementing towards the end of string.

如果字符串变量被声明为 var="HELLO PYTHON",那么字符串中各个字符的索引如下 −

If a string variable is declared as var="HELLO PYTHON", index of each character in the string is as follows −

string index

Python String Indexing

Python 允许你通过字符串的索引访问字符串中的任何单个字符。在这种情况下,0 是字符串的下界,11 是字符串的上界。所以,var[0] 返回 H,var[6] 返回 P。如果方括号中的索引超过上界,Python 会引发 IndexError。

Python allows you to access any individual character from the string by its index. In this case, 0 is the lower bound and 11 is the upper bound of the string. So, var[0] returns H, var[6] returns P. If the index in square brackets exceeds the upper bound, Python raises IndexError.

Example

在下面的示例中,我们通过索引访问字符串的字符。

In the below example, we accessing the characters of a string through index.

var = "HELLO PYTHON"
print(var[0])
print(var[7])
print(var[11])
print(var[12])

运行代码后,会生成以下输出 −

On running the code, it will produce the following output −

H
Y
N
ERROR!
Traceback (most recent call last):
  File "<main.py>", line 5, in <module>
IndexError: string index out of range

Python String Negative & Positive Indexing

Python 序列类型(因此也包括字符串对象)的一个独特特性是它也具有负索引方案。在上面的示例中,使用了正索引方案,其中索引从左到右递增。在负索引的情况下,末尾的字符的索引为 -1,索引从右到左递减,结果第一个字符 H 的索引为 -12。

One of the unique features of Python sequence types (and therefore a string object) is that it has a negative indexing scheme also. In the example above, a positive indexing scheme is used where the index increments from left to right. In case of negative indexing, the character at the end has -1 index and the index decrements from right to left, as a result the first character H has -12 index.

positive negative index

Example

让我们使用负索引获取 N、Y 和 H 字符。

Let us use negative indexing to fetch N, Y, and H characters.

var = "HELLO PYTHON"
print(var[-1])
print(var[-5])
print(var[-12])

执行上述代码时,将获得以下结果:

On executing the above code, it will give the following result −

N
Y
H

因此,我们可以使用正索引或负索引来从字符串中检索字符。

We can therefore use positive or negative index to retrieve a character from the string.

在 Python 中,字符串是不可修改的对象。如果将对象存储在特定内存位置后无法就地修改它,则它不可修改。您可以使用字符串的索引检索其中的任何字符,但不能用另一个字符替换它。

In Python, string is an immutable object. The object is immutable if it cannot be modified in-place, once stored in a certain memory location. You can retrieve any character from the string with the help of its index, but you cannot replace it with another character.

Example

在以下示例中,字符Y在字符串HELLO PYTHON中的索引为7。尝试用y替换Y,看看会发生什么。

In the following example, character Y is at index 7 in HELLO PYTHON. Try to replace Y with y and see what happens.

var="HELLO PYTHON"
var[7]="y"
print (var)

它将生成以下 output

It will produce the following output

Traceback (most recent call last):
 File "C:\Users\users\example.py", line 2, in <module>
  var[7]="y"
  ~~~^^^
TypeError: 'str' object does not support item assignment

TypeError 是因为字符串是不可变的。

The TypeError is because the string is immutable.

Python String Slicing

Python 将“:”定义为字符串切片运算符。它从原始字符串返回一个子字符串。它的常规用法如下:

Python defines ":" as string slicing operator. It returns a substring from the original string. Its general usage is as follows −

substr=var[x:y]

“:”运算符需要两个整数操作数(两个操作数都可以省略,如我们在后续示例中看到的)。第一个操作数 x 是所需的切片第一个字符的索引。第二个操作数 y 是所需的字符串中倒数第二个字符的索引。因此,var(x:y] 将字符从第 x 个位置分隔到第 (y-1) 个位置,从原始字符串中分隔。

The ":" operator needs two integer operands (both of which may be omitted, as we shall see in subsequent examples). The first operand x is the index of the first character of the desired slice. The second operand y is the index of the character next to the last in the desired string. So var(x:y] separates characters from xth position to (y-1)th position from the original string.

Example

var="HELLO PYTHON"

print ("var:",var)
print ("var[3:8]:", var[3:8])

它将生成以下 output

It will produce the following output

var: HELLO PYTHON
var[3:8]: LO PY

Python String Slicing With Negative Indexing

与正索引一样,负索引也可用于切片。

Like positive indexes, negative indexes can also be used for slicing.

Example

以下示例说明如何使用负索引对字符串进行切片。

The below example shows how to slice a string using negative indexes.

var="HELLO PYTHON"
print ("var:",var)
print ("var[3:8]:", var[3:8])
print ("var[-9:-4]:", var[-9:-4])

它将生成以下 output

It will produce the following output

var: HELLO PYTHON
var[3:8]: LO PY
var[-9:-4]: LO PY

Default Values of Indexes with String Slicing

Python Slice 运算符的两个操作数均为可选。第一个操作数默认为零,这意味着如果没有给出第一个操作数,那么切片从第 0 个索引处的字符开始,即第一个字符。它将切片左起 "y-1" 个字符的子字符串。

Both the operands for Python’s Slice operator are optional. The first operand defaults to zero, which means if we do not give the first operand, the slice starts of character at 0th index, i.e. the first character. It slices the leftmost substring up to "y-1" characters.

Example

在此示例中,我们使用默认值执行切片操作。

In this example, we are performing slice operation using default values.

var="HELLO PYTHON"
print ("var:",var)
print ("var[0:5]:", var[0:5])
print ("var[:5]:", var[:5])

它将生成以下 output

It will produce the following output

var: HELLO PYTHON
var[0:5]: HELLO
var[:5]: HELLO

Example

类似地,y 操作数也是可选的。默认值为 "-1",这意味着字符串将从第 x 个位置切片到字符串末尾。

Similarly, y operand is also optional. By default, it is "-1", which means the string will be sliced from the xth position up to the end of string.

var="HELLO PYTHON"
print ("var:",var)
print ("var[6:12]:", var[6:12])
print ("var[6:]:", var[6:])

它将生成如下输出:

It will produce the following output −

var: HELLO PYTHON
var[6:12]: PYTHON
var[6:]: PYTHON

Example

显然,如果两个操作数都没有使用,那么切片将等于原始字符串。这是因为 "x" 是 0,"y" 默认是最后一个索引加 1(或 -1)。

Naturally, if both the operands are not used, the slice will be equal to the original string. That’s because "x" is 0, and "y" is the last index+1 (or -1) by default.

var="HELLO PYTHON"
print ("var:",var)
print ("var[0:12]:", var[0:12])
print ("var[:]:", var[:])

它将生成以下 output

It will produce the following output

var: HELLO PYTHON
var[0:12]: HELLO PYTHON
var[:]: HELLO PYTHON

Example

左操作数必须小于右操作数,才能获取原始字符串的一个子字符串。如果左操作数更大,Python 不会引发任何错误,但会返回一个空字符串。

The left operand must be smaller than the operand on right, for getting a substring of the original string. Python doesn’t raise any error, if the left operand is greater, bu returns a null string.

var="HELLO PYTHON"
print ("var:",var)
print ("var[-1:7]:", var[-1:7])
print ("var[7:0]:", var[7:0])

它将生成以下 output

It will produce the following output

var: HELLO PYTHON
var[-1:7]:
var[7:0]:

Return Type of String Slicing

切片返回一个新字符串。你完全可以在切片字符串上执行字符串操作,如连接或切片。

Slicing returns a new string. You can very well perform string operations like concatenation, or slicing on the sliced string.

Example

var="HELLO PYTHON"

print ("var:",var)
print ("var[:6][:2]:", var[:6][:2])

var1=var[:6]
print ("slice:", var1)
print ("var1[:2]:", var1[:2])

它将生成以下 output

It will produce the following output

var: HELLO PYTHON
var[:6][:2]: HE
slice: HELLO
var1[:2]: HE