# Python 数字和字符串 > 原文: [https://javabeginnerstutorial.com/python-tutorial/python-numbers-and-strings-2/](https://javabeginnerstutorial.com/python-tutorial/python-numbers-and-strings-2/) 在本文中,我们将介绍 Python 3 数字和字符串,因为它们是使用 Python 开发的基础。 ## Python 3 数字 您可能已经想到,数字数据类型存储数字值,例如整数和浮点数。 尽管您应该了解数字的另一种类型:*复数*。 让我们简要看一下这三种数字。 * 整数(也称为整数)是没有小数点的整数,可以包含正数或负数。 只要您希望提供良好的计算可能性,整数就可以。 * 浮点数是浮点数,这意味着即使它们是整数,它们也包含一个小数点。 它们涵盖了一组实数,因此您可以对其进行任何操作。 * 大多数情况下,复数出于科学目的。 但是很高兴知道还有更多东西。 您可能从数学上知道复数表示为`+ bi`,其中`i`是表示 -1 的平方根的虚部。 **但是在 Python** 中,虚部表示为`j`,因此,如果要编写复数,则应执行:`c = 42 + 26j`。 ### 特殊数字 您也可以在 Python 中使用两个常用的数字(至少在数学上是如此)。 这些数字是`pi`和`e`。 要使用它们,您必须导入数学模块: ```py >>> import math >>> math.pi 3.141592653589793 >>> math.e 2.718281828459045 ``` ### 随机数 在一些书籍或教程的帮助下开始开发时,您会遇到随机数生成的问题。 稍后我们将使用随机数。 但是,现在是使用 Python 引入随机数生成的好时机。 为此,我们必须导入一个模块:`random`。 ```py >>> 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 ``` ## 字符串 字符串在 Python 中定义为引号之间表示的字符列表。 我们可以使用单引号(`'`或单引号)或双引号(`"`)来表示字符串。 我们可以在一个字符串中使用另一个字符串,但是如果您使用单引号将字符串开头,则也必须以该字符串结尾。 这些字符串是单行字符串,这意味着您无法将它们分散在多行中,这会导致错误。 但是,在讨论注释时,我们讨论了以三个引号开头的字符串(再次使用单引号或双引号也没有关系)。 它们可以通过多条线传播。 但是,它们会在最后转换为常规字符串,并且在写文本时仅在换行符(`\n`)处按回车符。 这种字符串最常见的用法是文档。 当我们到达函数和类时,我们将讨论这个主题。 让我们举个简单的示例: ```py >>> "this is a File "", line 1 "this is a ^ SyntaxError: EOL while scanning string literal >>> 'this is line " File "", 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' ``` ### 访问和更新字符串 Python 没有*字符*的显式类型,它们被视为长度为 1 的字符串。 访问字符串与访问任何其他变量相同。 不能就地更新字符串,因为字符串在 Python 中是不可变的类型。 如果您“更新”字符串的值,则仅使用新字符串重新分配该值。 ```py >>> s1 = "Hello World!" >>> id(s1) 4318883504 >>> s1 = "Hello Python!" >>> id(s1) 4318903344 >>> id('Hello World!') 4318883504 ``` ### 特殊字符串运算符 因为字符串是 Python 中的类型,被视为某种列表,所以字符串具有特殊的运算符,我们可以将其用于开发目的。 让我们用示例来看看它们。 在下一个小节中将对切片进行详细说明。 * `+`符号将字符串连接起来 * `*`符号创建字符串的多个副本 * `[int]`将字符串中给定位置(`int`)的字符切片 * `[int1:int2]`它获取给定范围内的字符(`int1 – int2`) * `[::int]`获取给定范围之间的字符,以及字符之间的步长(`int`) * `in`判断字符串中是否存在子字符串 * `not in`判断字符串中是否不存在子字符串 ```py >>> '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 ``` ### 三引号 我已经提到了我对三重引号的看法:它们是多行字符串而不是注释。 多行字符串表示它们与单行(或普通)字符串的打印方式相同,但保留其显式的新行并将特殊的转义字符转换为其打印版本。 ```py >>> 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! ``` 如您所见,当不打印字符串时,他的特殊转义符将保持转义-甚至在创建多行字符串时,我们在添加换行符的地方 Python 都显式显示`\n`。 ### 字符串格式化 字符串格式化在 Python 中很酷。 格式有两种版本:带`%`符号(类似于 C 的`printf`方法)和字符串本身的`format()`方法。 但是,在大多数情况下,我将同时介绍这两种版本,第二种版本更好,更易于使用。 让我们直接进入细节。 ```py >>> 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!' ``` 如您所见,两个格式化选项之间没有太大区别。 但是,如果您查看第一个版本,则可以看到变量使用的占位符(`%s`和`%d`)与第二个版本中的占位符不同。 关键是对于`%`格式,您必须告诉参数的类型以根据结果字符串中的格式启用 python。 这也意味着如果要多次打印变量,则必须重复变量。 格式函数与参数索引一起使用,并根据类型确定格式。 因此,您不必明确提及参数的类型。 如果您提供的参数数量与占位符相同,则可以保留参数索引。 ```py >>> '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 "", line 1, in 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!' ``` 取决于您以后使用哪种格式,但是在本系列文章中,我将坚持使用`format`函数。 但是,如果您更喜欢`%`,这里有一些字符以及它们在格式字符串中的作用: * **`%c`**:字符 * **`%s`**:格式化前通过`str()`进行字符串转换 * **`%i`**:带符号的十进制整数 * **`%d`**:带符号的十进制整数 * **`%u`**:无符号十进制整数 * **`%o`**:弱八进制 * **`%x`**:十六进制整数(小写字母) * **`%X`**:十六进制整数(大写字母) * **`%e`**:指数符号(小写的“`e`”) * **`%E`**:指数表示法(大写的“`E`”) * **`%f`**:浮点实数 * **`%g`**:`%f`和`%e`中的较短者 * **`%G`**:`%F`和`%E`中的较短者 ### 参考文献 * [官方文档](https://docs.python.org/3/library/numbers.html)