python3基础之数字与字符串

xiaoxiao2021-02-28  41

一、数字

1.整数(int)

In [1]: type(1) Out[1]: int

2.浮点数(float)

In [4]: type(1.0) Out[4]: float In [ ]: ### 3.数字运算 In [5]: type(1+1.0) Out[5]: float In [7]: type(1*1.0) Out[7]: float In [8]: type(1/1.0) Out[8]: float

注意:数字的四则运算结果向精度高的方向靠近

In [15]: 2/2 Out[15]: 1.0 In [16]: 2//2 Out[16]: 1 In [19]: 5%3 Out[19]: 2

注意:运算中/表示除法,结果为浮点数.//表示除法,结果为整数。%表示取余数,结果为整数

3.进制

X进制的意思是逢X进1

3.1 进制表示

In [ ]: # 二进制:0b10--2 # 八进制:0o10--8 # 十六进制:0x10--16

3.2 进制转换

In [24]: bin(10) # X进制转换二进制 Out[24]: '0b1010' In [25]: int(0o10) # X进制转换十进制 Out[25]: 8 In [26]: hex(10) # X进制转换十六进制 Out[26]: '0xa' In [27]: oct(10) # X进制转换八进制 Out[27]: '0o12'

4.bool类型

In [20]: bool(1) Out[20]: True In [21]: bool(0) Out[21]: False In [22]: bool('') Out[22]: False In [23]: bool('252') Out[23]: True

注意:只要是非空,非数字0,皆为True

二、字符串

In [29]: type('Hello, World!') Out[29]: str

1. 字符串表示

任何被' '," " ,''' '''。所包围的字符都可以视为字符串

2.字符串常见操作

2.1 切片

In [30]: 'Hello, World!'[0:5] Out[30]: 'Hello' In [33]: 'Hello, World!'[-6:] Out[33]: 'World!'

2.2 统计字符次数

In [34]: 'Hello, World!'.count('l') Out[34]: 3

2.3 查找字符位置

In [37]: 'Hello, World!'.find('e') Out[37]: 1

2.3 字符串打印

In [39]: 'Hello{}World{}'.format(",","!") Out[39]: 'Hello,World!' In [42]: 'Hello%sWorld%s'%(",","!") Out[42]: 'Hello,World!'

注意不要再用'Hello%sWorld%s'%(",","!") 这种形式了,强烈推荐用第一种,因为不需要确认字符的类型。

2.4 字符串拼接

In [46]: output =["Hello","World!"] In [47]: ','.join(output) Out[47]: 'Hello,World!'

2.5 字符串替换

In [48]: 'Hello, World!'.replace('!','.') Out[48]: 'Hello, World.'

2.6 字符串分割

In [49]: 'Hello, World!'.split(',') Out[49]: ['Hello', ' World!']

三、git地址

https://coding.net/u/RuoYun/p/Python-Programming-Notes/git/tree/master/0.basics/1.numbers_and_strings

转载请注明原文地址: https://www.6miu.com/read-2628406.html

最新回复(0)