Python 字符串就是一系列字符。本节将讨论如何创建字符串、访问单个字符(项)以及迭代字符。此外,还将展示字符串切片。
创建 Python 字符串
有多种方法可以创建字符串。这为您提供了创建字符串的思路。
# Create using Single Quote
Str1 = 'This is a message'
print(Str1)
# Create using Double Quote
Str2 = "This is another with Double Quotes"
print(Str2)
# Create using Multiple Single Quotes
Str3 = '''This also Work'''
print(Str3)
# Create it using Triple Quotes
# This is Very Useful to create Multiline Text
Str4 = """Learn Programming
at Tutorial Gateway"""
print(Str4)
This is a message
This is another with Double Quotes
This also Work
Learn Programming
at Tutorial Gateway
访问 Python 字符串项
我们可以使用索引访问字符串中的元素。使用索引,我们可以单独访问每个项。索引值从 0 开始,到 n-1 结束,其中 n 是长度。例如,如果长度为 5,则索引从 0 开始,到 4 结束。要访问第 1 个值,请使用 name[0],要访问第 5 个值,则使用 name[4]。
x = 'Tutorial Gateway'
# Positive Indexing
print(x[0])
print(x[4])
print(x[9])
print('=======\n')
# Negative
print(x[-3])
print(x[-7])
print(x[-16])
print('=======\n')
如果您使用负索引,它会从右到左查找项(此处,-1 是最后一个项,-2 是倒数第二个,依此类推)。
T
r
G
=======
w
G
T
=======
迭代字符串
Python For 循环是遍历字符串中字符或项最常用的方法。此代码可帮助我们迭代字符串,并打印字符串中存在的每个字符。
Str = "Python"
for word in Str:
print("Letters are: ", word)
上述代码可以很好地打印其中的字符。但是,要更改单个项,我们还需要Python索引位置。为了解决这个问题,我们必须将range 函数与 for 循环一起使用
for word in range(len(Str)):
print("Letters at index {0} is = {1}".format(word, Str[word]))

字符串连接
连接或组合多个字符串称为 Python 字符串连接或拼接。有多种方法可以进行连接。
- 我们可以使用 + 运算符连接多个字符串。
- 将多个字面量放在一起会自动连接它们。
- 将多个字符串放在一个括号 () 内
- * 运算符将句子重复给定次数。这里是三次。
在此示例中,我们向您展示如何对字符串使用算术运算符来执行算术运算。
X = 'Tutorial '
Y = 'Gateway'
# Using + Operator
Concat = X + Y
Concat1 = 'This ' + X
# Placing two Literals Together
Concat2 = 'Tutorial ' 'Gateway'
#Using Parentheses
Concat3 = ('Tutorial ' 'Gateway')
print(Concat)
print(Concat1)
print(Concat2)
print(Concat3)
# Using * Operator
Z = X * 3
print(Z)
Tutorial Gateway
This Tutorial
Tutorial Gateway
Tutorial Gateway
Tutorial Tutorial Tutorial
Python 字符串切片
在字符串切片中,第一个整数值是切片开始的索引位置,第二个是切片结束的索引位置,但不包括此索引位置的内容。例如,如果我们将 stritem[1:4],那么字符串切片从索引位置 1 开始,到索引位置 3 结束(而不是 4)。
x = 'Tutorial Gateway' # Using two a = x[2:13] print(a) # Using Second b = x[:8] print(b) # Slice using First c = x[4:] print(c) # without using two d = x[:] print(d) # Slice using Negative first e = x[-3:] print(e) # Slice using Negative second f = x[:-2] print(f)
torial Gate
Tutorial
rial Gateway
Tutorial Gateway
way
Tutorial Gatew
字符串切片分析
- 如果您省略第一个索引,切片将从头开始。
- 如果您省略第二个参数,切片将从第一个位置开始并继续到最后一个位置。
- 而且,如果您使用负数作为索引,切片将从右到左开始。