于 2020 年 1 月 10 日更新
python 中的字符串是由单引号或双引号分隔的连续字符系列。 Python 没有任何单独的字符数据类型,因此它们表示为单个字符串。
创建字符串
>>> name = "tom" # a string>>> mychar = 'a' # a character
您还可以使用以下语法创建字符串。
>>> name1 = str() # this will create empty string object>>> name2 = str("newstring") # string object containing 'newstring'
name = "tom" # a stringmychar = 'a' # a characterprint(name)print(mychar)name1 = str() # this will create empty string objectname2 = str("newstring") # string object containing 'newstring'print(name1)print(name2)
Python 中的字符串是不可变的
这对您而言意味着,一旦创建了字符串,便无法对其进行修改。 让我们以一个例子来说明这一点。
>>> str1 = "welcome">>> str2 = "welcome"
这里str1和str2指的是存储在内存中某个位置的相同字符串对象“welcome”。 您可以使用id()函数测试str1是否与str2引用相同的对象。
什么是身份证?
python 中的每个对象都存储在内存中的某个位置。 我们可以使用id()获得该内存地址。
>>> id(str1)78965411>>> id(str2)78965411
由于str1和str2都指向相同的存储位置,因此它们都指向同一对象。
让我们尝试通过向其添加新字符串来修改str1对象。
>>> str1 += " mike">>> str1welcome mike>>> id(str1)>>> 78965579
如您现在所见,str1指向完全不同的内存位置,这证明了并置不会修改原始字符串对象而是创建一个新的字符串对象这一点。 同样,数字(即int类型)也是不可变的。
试试看:
str1 = "welcome"str2 = "welcome"print(id(str1), id(str2))str1 += " mike"print(str1)print(id(str1))
字符串操作
字符串索引从0开始,因此要访问字符串类型中的第一个字符:
>>> name[0] #t
试一试:
name = "tom"print(name[0])print(name[1])
+运算符用于连接字符串,而*运算符是字符串的重复运算符。
>>> s = "tom and " + "jerry">>> print(s)tom and jerry
>>> s = "spamming is bad " * 3>>> print(s)'spamming is bad spamming is bad spamming is bad '
试一试:
s = "tom and " + "jerry"print(s)s = "spamming is bad " * 3print(s)
字符串切片
您可以使用[]运算符(也称为切片运算符)从原始字符串中提取字符串的子集。
语法:s[start:end]
这将从索引start到索引end - 1返回字符串的一部分。
让我们举一些例子。
>>> s = "Welcome">>> s[1:3]el
一些更多的例子。
>>> s = "Welcome">>>>>> s[:6]'Welcom'>>>>>> s[4:]'ome'>>>>>> s[1:-1]'elcom'
试一试:
s = "Welcome"print(s[1:3])print(s[:6])print(s[4:])print(s[1:-1])
注意:
start索引和end索引是可选的。 如果省略,则start索引的默认值为0,而end的默认值为字符串的最后一个索引。
ord()和chr()函数
ord()-函数返回字符的 ASCII 码。
chr()-函数返回由 ASCII 数字表示的字符。
>>> ch = 'b'>>> ord(ch)98>>> chr(97)'a'>>> ord('A')65
试一试:
ch = 'b'print(ord(ch))print(chr(97))print(ord('A'))
Python 中的字符串函数
| 函数名称 | 函数说明 |
|---|---|
len () |
返回字符串的长度 |
max() |
返回具有最高 ASCII 值的字符 |
min() |
返回具有最低 ASCII 值的字符 |
>>> len("hello")5>>> max("abc")'c'>>> min("abc")'a'
试一试:
print(len("hello"))print(max("abc"))print(min("abc"))
in和not in运算符
您可以使用in和not in运算符检查另一个字符串中是否存在一个字符串。 他们也被称为会员运营商。
>>> s1 = "Welcome">>> "come" in s1True>>> "come" not in s1False>>>
试一试:
s1 = "Welcome"print("come" in s1)print("come" not in s1)
字符串比较
您可以使用[>,<,<=,<=,==,!=)比较两个字符串。 Python 按字典顺序比较字符串,即使用字符的 ASCII 值。
假设您将str1设置为"Mary"并将str2设置为"Mac"。 比较str1和str2的前两个字符(M和M)。 由于它们相等,因此比较后两个字符。 因为它们也相等,所以比较了前两个字符(r和c)。 并且因为r具有比c更大的 ASCII 值,所以str1大于str2。
这里还有更多示例:
>>> "tim" == "tie"False>>> "free" != "freedom"True>>> "arrow" > "aron"True>>> "right" >= "left"True>>> "teeth" < "tee"False>>> "yellow" <= "fellow"False>>> "abc" > ""True>>>
试一试:
print("tim" == "tie")print("free" != "freedom")print("arrow" > "aron")print("right" >= "left")print("teeth" < "tee")print("yellow" <= "fellow")print("abc" > "")
使用for循环迭代字符串
字符串是一种序列类型,也可以使用for循环进行迭代(要了解有关for循环的更多信息,请单击此处)。
>>> s = "hello">>> for i in s:... print(i, end="")hello
注意:
默认情况下,print()函数用换行符打印字符串,我们通过传递名为end的命名关键字参数来更改此行为,如下所示。
print("my string", end="\n") # this is default behaviorprint("my string", end="") # print string without a newlineprint("my string", end="foo") # now print() will print foo after every string
试一试:
s = "hello"for i in s:print(i, end="")
测试字符串
python 中的字符串类具有各种内置方法,可用于检查不同类型的字符串。
| 方法名称 | 方法说明 |
|---|---|
isalnum() |
如果字符串是字母数字,则返回True |
isalpha() |
如果字符串仅包含字母,则返回True |
isdigit() |
如果字符串仅包含数字,则返回True |
isidentifier() |
返回True是字符串是有效的标识符 |
islower() |
如果字符串为小写,则返回True |
isupper() |
如果字符串为大写则返回True |
isspace() |
如果字符串仅包含空格,则返回True |
>>> s = "welcome to python">>> s.isalnum()False>>> "Welcome".isalpha()True>>> "2012".isdigit()True>>> "first Number".isidentifier()False>>> s.islower()True>>> "WELCOME".isupper()True>>> " \t".isspace()True
试一试:
s = "welcome to python"print(s.isalnum())print("Welcome".isalpha())print("2012".isdigit())print("first Number".isidentifier())print(s.islower())print("WELCOME".isupper())print(" \t".isspace())
搜索子串
| 方法名称 | 方法说明 |
|---|---|
endwith(s1: str): bool |
如果字符串以子字符串s1结尾,则返回True |
startswith(s1: str): bool |
如果字符串以子字符串s1开头,则返回True |
count(s: str): int |
返回字符串中子字符串出现的次数 |
find(s1): int |
返回字符串中s1起始处的最低索引,如果找不到字符串则返回-1 |
rfind(s1): int |
从字符串中s1的起始位置返回最高索引,如果找不到字符串则返回-1 |
>>> s = "welcome to python">>> s.endswith("thon")True>>> s.startswith("good")False>>> s.find("come")3>>> s.find("become")-1>>> s.rfind("o")15>>> s.count("o")3>>>
试一试:
s = "welcome to python"print(s.endswith("thon"))print(s.startswith("good"))print(s.find("come"))print(s.find("become"))print(s.rfind("o"))print(s.count("o"))
转换字符串
| 方法名称 | 方法说明 |
|---|---|
capitalize(): str |
返回此字符串的副本,仅第一个字符大写。 |
lower(): str |
通过将每个字符转换为小写来返回字符串 |
upper(): str |
通过将每个字符转换为大写来返回字符串 |
title(): str |
此函数通过大写字符串中每个单词的首字母来返回字符串 |
swapcase(): str |
返回一个字符串,其中小写字母转换为大写,大写字母转换为小写 |
replace(old, new): str |
此函数通过用新字符串替换旧字符串的出现来返回新字符串 |
s = "string in python">>>>>> s1 = s.capitalize()>>> s1'String in python'>>>>>> s2 = s.title()>>> s2'String In Python'>>>>>> s = "This Is Test">>> s3 = s.lower()>>> s3'this is test'>>>>>> s4 = s.upper()>>> s4'THIS IS TEST'>>>>>> s5 = s.swapcase()>>> s5'tHIS iS tEST'>>>>>> s6 = s.replace("Is", "Was")>>> s6'This Was Test'>>>>>> s'This Is Test'>>>
试一试:
s = "string in python"s1 = s.capitalize()print(s1)s2 = s.title()print(s2)s = "This Is Test"s3 = s.lower()print(s3)s4 = s.upper()print(s4)s5 = s.swapcase()print(s5)s6 = s.replace("Is", "Was")print(s6)print(s)
在下一章中,我们将学习 python 列表
