166.md 9.3 KB
Newer Older
W
wizardforcel 已提交
1
# Python 数字和字符串
W
init  
wizardforcel 已提交
2 3 4

> 原文: [https://javabeginnerstutorial.com/python-tutorial/python-numbers-and-strings-2/](https://javabeginnerstutorial.com/python-tutorial/python-numbers-and-strings-2/)

W
wizardforcel 已提交
5
在本文中,我们将介绍 Python 3 数字和字符串,因为它们是使用 Python 开发的基础。
W
init  
wizardforcel 已提交
6

W
wizardforcel 已提交
7
## Python 3 数字
W
init  
wizardforcel 已提交
8 9 10

您可能已经想到,数字数据类型存储数字值,例如整数和浮点数。 尽管您应该了解数字的另一种类型:*复数*。 让我们简要看一下这三种数字。

W
wizardforcel 已提交
11
*   整数(也称为整数)是没有小数点的整数,可以包含正数或负数。 只要您希望提供良好的计算可能性,整数就可以。
W
init  
wizardforcel 已提交
12
*   浮点数是浮点数,这意味着即使它们是整数,它们也包含一个小数点。 它们涵盖了一组实数,因此您可以对其进行任何操作。
W
wizardforcel 已提交
13
*   大多数情况下,复数出于科学目的。 但是很高兴知道还有更多东西。 您可能从数学上知道复数表示为`+ bi`,其中`i`是表示 -1 的平方根的虚部。 **但是在 Python** 中,虚部表示为`j`,因此,如果要编写复数,则应执行:`c = 42 + 26j`
W
init  
wizardforcel 已提交
14

W
wizardforcel 已提交
15
### 特殊数字
W
init  
wizardforcel 已提交
16

W
wizardforcel 已提交
17
您也可以在 Python 中使用两个常用的数字(至少在数学上是如此)。 这些数字是`pi``e`。 要使用它们,您必须导入数学模块:
W
init  
wizardforcel 已提交
18

W
wizardforcel 已提交
19
```py
W
init  
wizardforcel 已提交
20 21 22 23 24 25 26 27 28
>>> import math
>>> math.pi
3.141592653589793
>>> math.e
2.718281828459045
```

### 随机数

W
wizardforcel 已提交
29
在一些书籍或教程的帮助下开始开发时,您会遇到随机数生成的问题。 稍后我们将使用随机数。 但是,现在是使用 Python 引入随机数生成的好时机。
W
init  
wizardforcel 已提交
30

W
wizardforcel 已提交
31
为此,我们必须导入一个模块:`random`
W
init  
wizardforcel 已提交
32

W
wizardforcel 已提交
33
```py
W
init  
wizardforcel 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
>>> import random
>>> random.choice((1,2,3,4,'a')) # chooses one item of the provided list, tuple or string (it has to be an idexable object)
2
>>> random.random() # returns a random floating point number which is greater or equal to `0` and less than `1`
0.17489302862620337
>>> l = [1,2,3,4,5]
>>> >>> random.shuffle(l) # shuffles the list in place, returns `None`
>>> l
[1, 4, 3, 2, 5]
>>> random.randrange(1,10) # selects a random integer between the range of the first and the second parameter
4
>>> random.randrange(1,10,2) # the third parameter is an optional integer, defines the step in the range to select the elements from
5
```

W
wizardforcel 已提交
49
## 字符串
W
init  
wizardforcel 已提交
50

W
wizardforcel 已提交
51
字符串在 Python 中定义为引号之间表示的字符列表。 我们可以使用单引号(`'`或单引号)或双引号(`"`)来表示字符串。 我们可以在一个字符串中使用另一个字符串,但是如果您使用单引号将字符串开头,则也必须以该字符串结尾。
W
init  
wizardforcel 已提交
52

W
wizardforcel 已提交
53
这些字符串是单行字符串,这意味着您无法将它们分散在多行中,这会导致错误。 但是,在讨论注释时,我们讨论了以三个引号开头的字符串(再次使用单引号或双引号也没有关系)。 它们可以通过多条线传播。 但是,它们会在最后转换为常规字符串,并且在写文本时仅在换行符(`\n`)处按回车符。 这种字符串最常见的用法是文档。 当我们到达函数和类时,我们将讨论这个主题。
W
init  
wizardforcel 已提交
54

W
wizardforcel 已提交
55
让我们举个简单的示例:
W
init  
wizardforcel 已提交
56

W
wizardforcel 已提交
57
```py
W
init  
wizardforcel 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
>>> "this is a
File "<stdin>", line 1
   "this is a
             ^
SyntaxError: EOL while scanning string literal

>>> 'this is line "
  File "<stdin>", line 1 # Starting and ending of String should be done with same type of quote
    'this is line "
                  ^
SyntaxError: EOL while scanning string literal

>>> 'this will " work " without any isue'
'this will " work " without any isue'
>>> ''' this is a
... string'''
' this is a\nstring'
```

### 访问和更新字符串

W
wizardforcel 已提交
79
Python 没有*字符*的显式类型,它们被视为长度为 1 的字符串。 访问字符串与访问任何其他变量相同。
W
init  
wizardforcel 已提交
80

W
wizardforcel 已提交
81
不能就地更新字符串,因为字符串在 Python 中是不可变的类型。 如果您“更新”字符串的值,则仅使用新字符串重新分配该值。
W
init  
wizardforcel 已提交
82

W
wizardforcel 已提交
83
```py
W
init  
wizardforcel 已提交
84 85 86 87 88 89 90 91 92 93 94 95
>>> s1 = "Hello World!"
>>> id(s1)
4318883504
>>> s1 = "Hello Python!"
>>> id(s1)
4318903344
>>> id('Hello World!')
4318883504
```

### 特殊字符串运算符

W
wizardforcel 已提交
96
因为字符串是 Python 中的类型,被视为某种列表,所以字符串具有特殊的运算符,我们可以将其用于开发目的。 让我们用示例来看看它们。
W
init  
wizardforcel 已提交
97 98 99

在下一个小节中将对切片进行详细说明。

W
wizardforcel 已提交
100 101
*   `+`符号将字符串连接起来
*   `*`符号创建字符串的多个副本
W
wizardforcel 已提交
102 103 104
*   `[int]`将字符串中给定位置(`int`)的字符切片
*   `[int1:int2]`它获取给定范围内的字符(`int1 – int2`
*   `[::int]`获取给定范围之间的字符,以及字符之间的步长(`int`
W
wizardforcel 已提交
105 106
*   `in`判断字符串中是否存在子字符串
*   `not in`判断字符串中是否不存在子字符串
W
init  
wizardforcel 已提交
107

W
wizardforcel 已提交
108
```py
W
init  
wizardforcel 已提交
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
>>> 'Hello' + ' ' + "Python" # the + sign concatenates the strings
'Hello Python'
>>> 'Hello'+'!' * 5 # the * sign creates multiple copies of the string
'Hello!!!!!'
>>> "Python"[2] # slices the character at the given position out of the string
't'
>>> "Hello World!"[0:5] # gets the characters between the given range
'Hello'
>>> 'Hello World!'[::2] # gets the characters between the given range with the amount of steps between the characters
'HloWrd'
>>> 'llo' in "Hello World!" # looks up if a substring is present in the string
True
>>> "hell" not in 'Hello World!' # looks if a substring is not present in the string
True
```

### 三引号

我已经提到了我对三重引号的看法:它们是多行字符串而不是注释。

多行字符串表示它们与单行(或普通)字符串的打印方式相同,但保留其显式的新行并将特殊的转义字符转换为其打印版本。

W
wizardforcel 已提交
131
```py
W
init  
wizardforcel 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
>>> spam = """Spam, Spam, Spam, lovely Spam
... Wonderful Spam, Lovely Spam.
... Spam, Spam, Spam, magnificent Spam,
... \tSuperlative Spam.
... Spam, Spam, Spam, wonderous Spam,\nSurgical Spam, splendiferous Spam.
... Eggs, Bacon, sausage!\rSpam, Spam, Spam, Spaaam!"""
>>> spam
'Spam, Spam, Spam, lovely Spam\nWonderful Spam, Lovely Spam.\nSpam, Spam, Spam, magnificent Spam,\n\tSuperlative Spam.\nSpam, Spam, Spam, wonderous Spam,\nSurgical Spam, splendiferous Spam.\nEggs, Bacon, sausage!\rSpam, Spam, Spam, Spaaam!'
>>> print(spam)
Spam, Spam, Spam, lovely Spam
Wonderful Spam, Lovely Spam.
Spam, Spam, Spam, magnificent Spam,
   Superlative Spam.
Spam, Spam, Spam, wonderous Spam,
Surgical Spam, splendiferous Spam.
Spam, Spam, Spam, Spaaam!
```

W
wizardforcel 已提交
150
如您所见,当不打印字符串时,他的特殊转义符将保持转义-甚至在创建多行字符串时,我们在添加换行符的地方 Python 都显式显示`\n`
W
init  
wizardforcel 已提交
151

W
wizardforcel 已提交
152
### 字符串格式化
W
init  
wizardforcel 已提交
153

W
wizardforcel 已提交
154
字符串格式化在 Python 中很酷。 格式有两种版本:带`%`符号(类似于 C 的`printf`方法)和字符串本身的`format()`方法。 但是,在大多数情况下,我将同时介绍这两种版本,第二种版本更好,更易于使用。
W
init  
wizardforcel 已提交
155 156 157

让我们直接进入细节。

W
wizardforcel 已提交
158
```py
W
init  
wizardforcel 已提交
159 160 161 162 163 164 165 166 167 168
>>> name = 'Bob'
>>> age = 31
>>> 'My name is %s and I am %d years young!'%(name, age)
'My name is Bob and I am 31 years young!'
>>> 'My name is {} and I am {} years young!'.format(name, age)
'My name is Bob and I am 31 years young!'
>>> 'My name is {0} and I am {1} years young!'.format(name, age)
'My name is Bob and I am 31 years young!'
```

W
wizardforcel 已提交
169
如您所见,两个格式化选项之间没有太大区别。 但是,如果您查看第一个版本,则可以看到变量使用的占位符(`%s``%d`)与第二个版本中的占位符不同。
W
init  
wizardforcel 已提交
170

W
wizardforcel 已提交
171
关键是对于`%`格式,您必须告诉参数的类型以根据结果字符串中的格式启用 python。 这也意味着如果要多次打印变量,则必须重复变量。
W
init  
wizardforcel 已提交
172 173 174

格式函数与参数索引一起使用,并根据类型确定格式。 因此,您不必明确提及参数的类型。 如果您提供的参数数量与占位符相同,则可以保留参数索引。

W
wizardforcel 已提交
175
```py
W
init  
wizardforcel 已提交
176 177 178 179 180 181 182 183 184 185 186 187
>>> 'My name is %s and I am %d years young and I have read %d books!'%(name, age, age)
'My name is Bob and I am 31 years young and I have read 31 books!'
>>> 'My name is {} and I am {} years young and I have read {} books!'.format(name, age)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> 'My name is {} and I am {} years young and I have read {} books!'.format(name, age, age)
'My name is Bob and I am 31 years young and I have read 31 books!'
>>> 'My name is {0} and I am {1} years young and I have read {1} books!'.format(name, age)
'My name is Bob and I am 31 years young and I have read 31 books!'
```

W
wizardforcel 已提交
188
取决于您以后使用哪种格式,但是在本系列文章中,我将坚持使用`format`函数。 但是,如果您更喜欢`%`,这里有一些字符以及它们在格式字符串中的作用:
W
wizardforcel 已提交
189

W
wizardforcel 已提交
190
*   **`%c`**:字符
W
wizardforcel 已提交
191
*   **`%s`**:格式化前通过`str()`进行字符串转换
W
wizardforcel 已提交
192 193 194 195 196 197
*   **`%i`**:带符号的十进制整数
*   **`%d`**:带符号的十进制整数
*   **`%u`**:无符号十进制整数
*   **`%o`**:弱八进制
*   **`%x`**:十六进制整数(小写字母)
*   **`%X`**:十六进制整数(大写字母)
W
wizardforcel 已提交
198 199
*   **`%e`**:指数符号(小写的“`e`”)
*   **`%E`**:指数表示法(大写的“`E`”)
W
wizardforcel 已提交
200
*   **`%f`**:浮点实数
W
wizardforcel 已提交
201 202
*   **`%g`**`%f``%e`中的较短者
*   **`%G`**`%F``%E`中的较短者
W
init  
wizardforcel 已提交
203 204 205

### 参考文献

W
wizardforcel 已提交
206
*   [官方文档](https://docs.python.org/3/library/numbers.html)
W
init  
wizardforcel 已提交
207