Python 基础:字符串

发布日期:2026-07-20 00:55:06  来源 : 杭州电子商务研究院    浏览量 :0
杭州电子商务研究院 发布日期:2026-07-20 00:55:06  
0

介绍

处理文本是一项常见的编程任务。Python 有一个内置的数据类型,专门用于此目的:str - 字符串。字符串用于以人类易于理解的形式显示数据、收集用户输入和存储信息。文本信息还可以在高度复杂的场景中进行分析,例如对围绕某个主题的社交媒体评论进行情绪分析。无论用途如何,字符串都是许多编程语言中非常重要的基本数据类型,Python 也不例外。本指南将向您展示一些字符串基础知识,提供理解 Python 中字符串的性质和用法的关键。

字符串保存文本

上一指南中,我们看到了一些分配给变量并使用print()显示的简单字符串。字符串旨在保存文本。更正式地说:Python 中的字符串是一种保存Unicode代码点序列的结构。这里的重要区别是 Unicode 中的字符不一定是单个 ASCII 字节,因此 Python 中的字符串可以表示任何语言中的任何字符。这使得字符串非常适合任何类型的文本处理。

我刚才提到了“序列”这个词。字符串可以包含零个或多个字符,因此具有长度的概念,我们将在本指南的稍后部分讨论。但首先:我们如何告诉 Python 某个东西是字符串?

文字

当 Python 解释器看到由单引号或双引号包围的字符序列时,它就知道您提供的是字符串文字。

      >>> a = 'marklar'
>>> b = "marklar marklar"
    

上面的变量ab被理解为包含一个字符串。等号右侧的引号文本被解释器理解为字符串文字,因为它被引号包围。您可以使用单引号'或双引号"来包围文本,只要开始和结束引号相同即可。

对于可能超出屏幕宽度的较长文本,或者如果您想在文本中添加一些换行符,则可以使用三重引号:

      >>> mailing_address = """Chip Marklar
... 123 Main street
... Zork City
... Planet Goof"""
>>>
>>> print(mailing_address)
Chip Marklar
123 Main street
Zork City
Planet Goof
>>>
    

当我们在解释器中将一个三引号字符串赋值给变量mailing_address时,解释器知道该字符串在第一行之后没有“闭合”,因此它会打印出三个点,以等待更多输入或匹配的闭合三引号。一旦接受最后一个引号,变量mailing_address最终就会被赋值。当我们打印变量时,会显示四行。这是因为输入的换行符(当您在输入的地址行之间按 Enter 键时)也会被捕获到字符串中。

分配没有换行符的长字符串文字也很容易:

      >>> a = 'Supercalifragilistic' 'expialidocious'
>>> print(a)
Supercalifragilisticexpialidocious

>>> b =  'Supercalifragilistic' \
... 'expialidocious'
>>> print(b)
Supercalifragilisticexpialidocious
>>>
    

上面,变量a被分配了一个使用两个文字部分的字符串。Python 查看两个带引号的字符串并将它们合并为一个。即使两个文字之间有空格,python 也不会在两个字符串之间添加空格。生成的字符串中没有空格 - 它是一个长文本。

Python 允许您通过在行尾添加反斜杠\来明确延续长行。变量b也由两个字符串文字赋值,python 将程序中两个可见行上的这两个文字混合在一起,但对它们的处理方式与它们存在于一个可见行上一样。请注意,python 没有添加任何空格 - 结果是两部分之间没有空格的文本 - 也没有添加任何换行符。使用这种技术,您可以将长文本值分配给跨多行的变量,而无需在文本中引入任何换行符。

但是,如果你确实想在字符串中引入换行符,该怎么办? Python 允许你使用转义序列来表示一小组特殊字符。换行符表示为\n

      >>> a = 'Chip\nMarklar'
>>> print(a)
Chip
Marklar
>>>
    

反斜杠\字符用于启动转义序列。您需要转义序列来表示难以输入或难以解释的字符。一些常见的转义序列是:

特点 转义序列
换行符 \n
Tab \t
单引号 \'
双引号 \”
反斜杠 \\
      >>> text = 'The c:\\temp folder has temporary files\n\tBut don\'t quote me on that!'
>>> print(text)
The c:\temp folder has temporary files
        But don't quote me on that!
>>>
    

在上面的例子中,文件夹路径中的反斜杠被加了引号,否则它将被解释为制表符\t。单词don't中的单引号也被加了引号,因为我不想让 python 认为字符串在那里结束,而不是在行尾。您可以通过明智地选择引号或使用原始字符串前缀来避免使用转义字符:

      a = r'c:\temp'
b = "Doesn't break"
    

The prefix r before the string literal assigned to a tells python to digest the backslash as a plain character. By using a double-quote around the string assigned to b, the single-quote in the word Doesn't is digested as a plain character as well, and python does not "close" the string until the matching double-quote at the end of that literal.

Comparing Strings

How can we compare strings? How do we tell if two strings contain the same word or text? Python string can be compared for equality and order.

      >>> 'Chip' == 'Chip'
True
>>> 'Chip' == 'Marklar'
False
>>> 'Chip' != 'Marklar'
True
>>> 'a' < 'a'
True
>>>
    

As you might expect, two strings of the same content are equal ('Chip' and 'Chip'), and two strings with different content are never equal. The not-equal != can be used to express non-equality. Comparing strings using < or > lets you know which string precedes (is "smaller" lexicographically) the other in alphabetical order. Take special care when strings contain numbers though:

      >>> '10' > '9'
False
>>>
    

The string '10' is "smaller" than the string '9' because the character 1 is smaller than 9, and these are taken as strings - not the numerical values they may appear to be.

Python string comparison is case sensitive.

      >>> 'Chip' == 'chip'
False
    

An easy way to compare strings without regards to case, is to convert them to lower or upper case. This can be done using the .upper() or .lower() methods:

      >>> 'Chip'.lower() == 'chip'
True
>>> 'Chip'.upper() == 'CHIP'
True
>>>
    

Manipulating Strings

Strings in Python are immutable - once created they are not modifiable. Variables may be assigned another string but that doesn't modify the original string. Consider this code:

      >>> a  = 'Chip'
>>> b = a
>>> a is b
True
>>> a = a + ' Marklar'
>>> a is b
False
>>> a
'Chip Marklar'
>>> b
'Chip'
>>>
    

Above I assign the value 'Chip' to the variable a and then assign that same string to variable b. Both a and b actually point to the same internal string containing 'Chip'. Using the is comparison operator confirms this: is returns True when both variables point to the same object in memory.

But when we then attempt to modify the string assigned to a, we actually create a new string. Even though a seems to start with the same sequence, they are totally different from each other. The original string remains and b points to it.

One obvious difference between a and b at this point is that they have different lengths. The length of a string can be obtained by using the len() method:

      >>> len('Marklar')
7
>>> len('\t')
1
>>> len('')
0
>>>
    

字符串的长度是其包含的 Unicode 字符数(更严格地说是代码点数)。在上面的例子中,我们看到单词“Marklar”有七个字符,制表符为一个字符,而空字符串的长度为零。

字符串不能被修改,但如果需要字符串的一部分,您可以将其切分并使用其中的一部分:

      >>> initials = 'Chip'[0] + 'Marklar'[0]
>>> print(initials)
CM
>>>
    

使用方括号,您可以根据字符与字符串开头的偏移量对字符串中的字符进行索引(指向)。零是第一个字符,因此在上面的示例中,我通过将姓名的两个部分的第一个字符拼合在一起来创建首字母。

      >>> word = 'HELLO!'
>>> proper = word[0] + word[1:5].lower()
>>> print(proper)
Hello
>>>
    

要从字符串中获取单个字符,请在方括号中指定单个下标。'HELLO'[0]'H''HELLO'[1]'E',依此类推。字符串'HELLO!'[0]的片段实际上是一个单字符的字符串,而不是数据类型字符。

如果您想要几个字符,请提供字符串的起始和结束偏移量。在上面的例子中,通过使用下标一作为起点、五作为最后一个字符(含)来切出第二到第五个字符,使变量适当地“正确大小写”。偏移量从零开始,因此E下标为1。当您想要从某个位置到字符串末尾的子字符串时,您可以省略第二个下标。以下两个表达式是等效的:

      >>> print( 'Chip Marklar'[5:12])
Marklar
>>> print( 'Chip Marklar'[5:])
Marklar
>>>
    

您还可以使用负整数指定字符串末尾的偏移量:

      >>> print( 'Marklar!'[0:-1])
Marklar
>>>
    

上面的例子从字符串中提取了第一个到倒数第二个字符的序列。我喜欢将负下标读作“除了最后 n 个字符”。与第二个下标一样,如果您想要字符串开头的所有字符,则可以省略第一个偏移量并写入:

      >>> print('Marklar!'[:-1])
'Marklar'
>>>
    

正如我所提到的,返回的字符串切片是一个字符串。但它不会修改原始字符串,也不原始字符串。如果我们将字符串的第一部分切分,我们实际上会得到一个新的字符串,它由原始字符串的切片填充:

      >>> a = 'Chip Marklar'
>>> b = a[0:4]
>>>
>>> print(a)
Chip Marklar
>>> print(b)
Chip
>>>
>>> print(a is b)
False
>>>
    

尽管a<font s

以上内容来自杭州电子商务研究院推送
分享到:

长按或扫码识别 分享给好友

长按或扫码识别 分享给好友
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据