Python-字符串运算符

时间:2020-02-23 14:43:29  来源:igfitidea点击:

在本教程中,我们将学习在Python中对字符串进行操作。

##连接字符串

我们可以使用+运算符连接两个字符串值。

在下面的示例中,我们将两个字符串连接起来以获得第三个字符串。

# strings
str1 = "Hello"
str2 = "World"

# concat
result = str1 + " " + str2

# output
print(result);

上面的程序将连接(联接)第一个字符串" str1",后跟一个空格,然后连接第二个字符串" str2"。

因此,我们将获得以下输出" Hello World"。

复制字符串

我们可以使用*操作符将给定的字符串复制N次。

在下面的示例中,我们将字符串" HA"复制3次。

# string
str = "HA"

# replicate
result = str * 3

# output
print(result)

上面的代码将给我们一个新的字符串HAHAHA

检查是否属于字符串-in

我们可以使用in运算符来检查给定字符串中是否存在搜索字符串。
如果找到搜索字符串,则返回True,否则返回False。

在下面的Python程序中,我们将检查在给定的字符串" Hello World"中是否存在搜索字符串" lo"。

# strings
needle = "lo"
haystack = "Hello World"

# check
if needle in haystack:
  print(needle, "is present in the string", haystack)
else:
  print("Not found")

对于上述程序,我们将获得以下输出。

lo is present in the string Hello World

检查是否不属于字符串-not in

我们可以使用not in运算符来检查给定字符串中是否不存在搜索字符串。
如果未找到搜索字符串,则为True,否则为False。

在下面的Python程序中,我们正在检查在给定的字符串" Hello World"中是否存在搜索字符串" HA"。

# strings
needle = "HA"
haystack = "Hello World"

# check
if needle in haystack:
  print(needle, "is present in the string", haystack)
else:
  print("Not found")

我们将得到"未找到"作为上述代码的输出。

访问字符串中的字符

我们使用str [i]来获得给定字符串str中i索引处的字符。

索引从0开始,因此,第一个字符在索引0处,第二个字符在1处,依此类推。

在下面的示例中,我们从字符串" Jane Doe"中提取第二个字符(索引1)。

# string
str = "Jane Doe"

# character
ch = str[1]

# output
print(ch)      # a

子字符串

我们使用str [start:end]从给定的字符串中获取子字符串。

我们从"开始"索引开始,提取子字符串,直到"结束"索引,但不包括它。

在下面的示例中,我们从字符串" Hello World"中提取子字符串" lo"。

# string
str = "Hello World"

# substring
substr = str[3:5]

# output
print(substr)     # lo

跳过字符

我们可以使用str [start:end:step]跳过字符串中的字符。

其中," start"是起始索引。
" end"代表直到提取字符串为止的最后一个索引(不包括在内),而" step"则是要执行的步骤数。

在下面的示例中,对于给定的字符串" Hello World",我们跳过1个字符。

字符串" Hello World"有11个字符,我们要跳过奇数索引字符,因此,步骤将为2。

因为我们正在考虑整个字符串,所以我们可以忽略end
我们将使用str [start :: step]

因此,我们将考虑以下字符:0-> 2-> 4-> 6-> 8-> 10。

string:    Hello World
skipping:   x x x x x    # characters marked with x
final str: HloWrd
# string
str = "Hello World"

# skip
new_str = str[0::2]

反转字符串

在Python中反转字符串的最简单方法是编写" str [::-1]"。

在下面的Python程序中,我们将反转字符串" Hello World"。

# string
str = "Hello World"

# reverse
result = str[::-1]

# output
print(result)

上面的代码将为我们提供以下输出dlroW olleH

转义序列

转义序列表示不可打印的字符。
他们以反斜杠开头。

以下是一些转义序列。

描述转义序列符号
警报或者响铃\ a
退格\ b
Escape\ e
换页\ f
换行\ n
回车\ r
空格\ s
制表符\t