mirror of
https://github.com/Estom/notes.git
synced 2026-06-14 22:28:17 +08:00
537 lines
9.1 KiB
Markdown
537 lines
9.1 KiB
Markdown
# Python 字符串
|
||
|
||
> 原文: [https://thepythonguru.com/python-strings/](https://thepythonguru.com/python-strings/)
|
||
|
||
* * *
|
||
|
||
于 2020 年 1 月 10 日更新
|
||
|
||
* * *
|
||
|
||
python 中的字符串是由单引号或双引号分隔的连续字符系列。 Python 没有任何单独的字符数据类型,因此它们表示为单个字符串。
|
||
|
||
## 创建字符串
|
||
|
||
* * *
|
||
|
||
```py
|
||
>>> name = "tom" # a string
|
||
>>> mychar = 'a' # a character
|
||
|
||
```
|
||
|
||
您还可以使用以下语法创建字符串。
|
||
|
||
```py
|
||
>>> name1 = str() # this will create empty string object
|
||
>>> name2 = str("newstring") # string object containing 'newstring'
|
||
|
||
```
|
||
|
||
```py
|
||
name = "tom" # a string
|
||
mychar = 'a' # a character
|
||
|
||
print(name)
|
||
print(mychar)
|
||
|
||
name1 = str() # this will create empty string object
|
||
name2 = str("newstring") # string object containing 'newstring'
|
||
|
||
print(name1)
|
||
print(name2)
|
||
```
|
||
|
||
## Python 中的字符串是不可变的
|
||
|
||
* * *
|
||
|
||
这对您而言意味着,一旦创建了字符串,便无法对其进行修改。 让我们以一个例子来说明这一点。
|
||
|
||
```py
|
||
>>> str1 = "welcome"
|
||
>>> str2 = "welcome"
|
||
|
||
```
|
||
|
||
这里`str1`和`str2`指的是存储在内存中某个位置的相同字符串对象“`welcome`”。 您可以使用[`id()`](/python-builtin-functions/id/)函数测试`str1`是否与`str2`引用相同的对象。
|
||
|
||
什么是身份证?
|
||
|
||
python 中的每个对象都存储在内存中的某个位置。 我们可以使用`id()`获得该内存地址。
|
||
|
||
```py
|
||
>>> id(str1)
|
||
78965411
|
||
>>> id(str2)
|
||
78965411
|
||
|
||
```
|
||
|
||
由于`str1`和`str2`都指向相同的存储位置,因此它们都指向同一对象。
|
||
|
||
让我们尝试通过向其添加新字符串来修改`str1`对象。
|
||
|
||
```py
|
||
>>> str1 += " mike"
|
||
>>> str1
|
||
welcome mike
|
||
>>> id(str1)
|
||
>>> 78965579
|
||
|
||
```
|
||
|
||
如您现在所见,`str1`指向完全不同的内存位置,这证明了并置不会修改原始字符串对象而是创建一个新的字符串对象这一点。 同样,数字(即`int`类型)也是不可变的。
|
||
|
||
试试看:
|
||
|
||
```py
|
||
str1 = "welcome"
|
||
str2 = "welcome"
|
||
|
||
print(id(str1), id(str2))
|
||
|
||
str1 += " mike"
|
||
|
||
print(str1)
|
||
|
||
print(id(str1))
|
||
```
|
||
|
||
## 字符串操作
|
||
|
||
* * *
|
||
|
||
字符串索引从`0`开始,因此要访问字符串类型中的第一个字符:
|
||
|
||
```py
|
||
>>> name[0] #
|
||
t
|
||
|
||
```
|
||
|
||
试一试:
|
||
|
||
```py
|
||
name = "tom"
|
||
|
||
print(name[0])
|
||
print(name[1])
|
||
```
|
||
|
||
`+`运算符用于连接字符串,而`*`运算符是字符串的重复运算符。
|
||
|
||
```py
|
||
>>> s = "tom and " + "jerry"
|
||
>>> print(s)
|
||
tom and jerry
|
||
|
||
```
|
||
|
||
```py
|
||
>>> s = "spamming is bad " * 3
|
||
>>> print(s)
|
||
'spamming is bad spamming is bad spamming is bad '
|
||
|
||
```
|
||
|
||
试一试:
|
||
|
||
```py
|
||
s = "tom and " + "jerry"
|
||
print(s)
|
||
|
||
s = "spamming is bad " * 3
|
||
print(s)
|
||
```
|
||
|
||
## 字符串切片
|
||
|
||
* * *
|
||
|
||
您可以使用`[]`运算符(也称为切片运算符)从原始字符串中提取字符串的子集。
|
||
|
||
**语法**:`s[start:end]`
|
||
|
||
这将从索引`start`到索引`end - 1`返回字符串的一部分。
|
||
|
||
让我们举一些例子。
|
||
|
||
```py
|
||
>>> s = "Welcome"
|
||
>>> s[1:3]
|
||
el
|
||
|
||
```
|
||
|
||
一些更多的例子。
|
||
|
||
```py
|
||
>>> s = "Welcome"
|
||
>>>
|
||
>>> s[:6]
|
||
'Welcom'
|
||
>>>
|
||
>>> s[4:]
|
||
'ome'
|
||
>>>
|
||
>>> s[1:-1]
|
||
'elcom'
|
||
|
||
```
|
||
|
||
试一试:
|
||
|
||
```py
|
||
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 数字表示的字符。
|
||
|
||
```py
|
||
>>> ch = 'b'
|
||
>>> ord(ch)
|
||
98
|
||
>>> chr(97)
|
||
'a'
|
||
>>> ord('A')
|
||
65
|
||
|
||
```
|
||
|
||
试一试:
|
||
|
||
```py
|
||
ch = 'b'
|
||
|
||
print(ord(ch))
|
||
|
||
print(chr(97))
|
||
|
||
print(ord('A'))
|
||
```
|
||
|
||
## Python 中的字符串函数
|
||
|
||
* * *
|
||
|
||
| 函数名称 | 函数说明 |
|
||
| --- | --- |
|
||
| `len ()` | 返回字符串的长度 |
|
||
| `max()` | 返回具有最高 ASCII 值的字符 |
|
||
| `min()` | 返回具有最低 ASCII 值的字符 |
|
||
|
||
```py
|
||
>>> len("hello")
|
||
5
|
||
>>> max("abc")
|
||
'c'
|
||
>>> min("abc")
|
||
'a'
|
||
|
||
```
|
||
|
||
试一试:
|
||
|
||
```py
|
||
print(len("hello"))
|
||
|
||
print(max("abc"))
|
||
|
||
print(min("abc"))
|
||
```
|
||
|
||
## `in`和`not in`运算符
|
||
|
||
* * *
|
||
|
||
您可以使用`in`和`not in`运算符检查另一个字符串中是否存在一个字符串。 他们也被称为会员运营商。
|
||
|
||
```py
|
||
>>> s1 = "Welcome"
|
||
>>> "come" in s1
|
||
True
|
||
>>> "come" not in s1
|
||
False
|
||
>>>
|
||
|
||
```
|
||
|
||
试一试:
|
||
|
||
```py
|
||
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`。
|
||
|
||
这里还有更多示例:
|
||
|
||
```py
|
||
>>> "tim" == "tie"
|
||
False
|
||
>>> "free" != "freedom"
|
||
True
|
||
>>> "arrow" > "aron"
|
||
True
|
||
>>> "right" >= "left"
|
||
True
|
||
>>> "teeth" < "tee"
|
||
False
|
||
>>> "yellow" <= "fellow"
|
||
False
|
||
>>> "abc" > ""
|
||
True
|
||
>>>
|
||
|
||
```
|
||
|
||
试一试:
|
||
|
||
```py
|
||
print("tim" == "tie")
|
||
|
||
print("free" != "freedom")
|
||
|
||
print("arrow" > "aron")
|
||
|
||
print("right" >= "left")
|
||
|
||
print("teeth" < "tee")
|
||
|
||
print("yellow" <= "fellow")
|
||
|
||
print("abc" > "")
|
||
```
|
||
|
||
## 使用`for`循环迭代字符串
|
||
|
||
* * *
|
||
|
||
字符串是一种序列类型,也可以使用`for`循环进行迭代(要了解有关`for`循环的更多信息,[请单击此处](/python-loops/))。
|
||
|
||
```py
|
||
>>> s = "hello"
|
||
>>> for i in s:
|
||
... print(i, end="")
|
||
hello
|
||
|
||
```
|
||
|
||
**注意**:
|
||
|
||
默认情况下,`print()`函数用换行符打印字符串,我们通过传递名为`end`的命名关键字参数来更改此行为,如下所示。
|
||
|
||
```py
|
||
print("my string", end="\n") # this is default behavior
|
||
print("my string", end="") # print string without a newline
|
||
print("my string", end="foo") # now print() will print foo after every string
|
||
|
||
```
|
||
|
||
试一试:
|
||
|
||
```py
|
||
s = "hello"
|
||
for i in s:
|
||
print(i, end="")
|
||
```
|
||
|
||
## 测试字符串
|
||
|
||
* * *
|
||
|
||
python 中的字符串类具有各种内置方法,可用于检查不同类型的字符串。
|
||
|
||
| 方法名称 | 方法说明 |
|
||
| --- | --- |
|
||
| `isalnum()` | 如果字符串是字母数字,则返回`True` |
|
||
| `isalpha()` | 如果字符串仅包含字母,则返回`True` |
|
||
| `isdigit()` | 如果字符串仅包含数字,则返回`True` |
|
||
| `isidentifier()` | 返回`True`是字符串是有效的标识符 |
|
||
| `islower()` | 如果字符串为小写,则返回`True` |
|
||
| `isupper()` | 如果字符串为大写则返回`True` |
|
||
| `isspace()` | 如果字符串仅包含空格,则返回`True` |
|
||
|
||
```py
|
||
>>> 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
|
||
|
||
```
|
||
|
||
试一试:
|
||
|
||
```py
|
||
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` |
|
||
|
||
```py
|
||
>>> 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
|
||
>>>
|
||
|
||
```
|
||
|
||
试一试:
|
||
|
||
```py
|
||
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` | 此函数通过用新字符串替换旧字符串的出现来返回新字符串 |
|
||
|
||
```py
|
||
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'
|
||
>>>
|
||
|
||
```
|
||
|
||
试一试:
|
||
|
||
```py
|
||
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)
|
||
```
|
||
|