Python程序员

【python基础】2-数值和字符串数据类型

2018-02-21  本文已影响70人  王诗翔

Python会自动确定变量数据类型。变量在其他地方使用之前仅需要赋值。

数值

>>> num1 = 7
>>> num2 = 42
>>> total = num1 + num2
>>> print(total)
49
>>> total
49

# 对整数精度没有限制,仅受限于可分配的内存
>>> 34 ** 32
10170102859315411774579628461341138023025901305856

# 使用单个 / (除法)会返回浮点结果
>>> 9 / 5
1.8

# 使用两个 / (整除)仅返回整数部分(没有取舍)
>>> 9 // 5
1

>>> 9 % 5
4
>>> appx_pi = 22 / 7
>>> appx_pi
3.142857142857143

>>> area = 42.16
>>> appx_pi + area
45.30285714285714

>>> num1
7
>>> num1 + area
49.16
>>> sci_num1 = 3.982e5
>>> sci_num2 = 9.32e-1
>>> sci_num1 + sci_num2
398200.932

>>> 2.13e21 + 5.23e22
5.443e+22
>>> bin_num = 0b101
>>> oct_num = 0o12
>>> hex_num = 0xF

>>> bin_num
5
>>> oct_num
10
>>> hex_num
15

>>> oct_num + hex_num
25
>>> 1_000_000
1000000
>>> 1_00.3_352
100.3352
>>> 0xff_ab1
1047217

# f-strings格式在后面章节解释
>>> num = 34 ** 32
>>> print(f'{num:_}')
10_170_102_859_315_411_774_579_628_461_341_138_023_025_901_305_856

进一步阅读

字符串

>>> str1 = 'This is a string'
>>> str1
'This is a string'
>>> greeting = "Hello World!"
>>> greeting
'Hello World!'

>>> weather = "It's a nice and warm day"
>>> weather
"It's a nice and warm day"
>>> print(weather)
It's a nice and warm day

>>> weather = 'It\'s a nice and warm day'
>>> print(weather)
It's a nice and warm day
>>> colors = 'Blue\nRed\nGreen'
>>> colors
'Blue\nRed\nGreen'

>>> print(colors)
Blue
Red
Green
>>> raw_str = r'Blue\nRed\nGreen'
>>> print(raw_str)
Blue\nRed\nGreen

# 查看字符串内部是如何存储的
>>> raw_str
'Blue\\nRed\\nGreen'
>>> str1 = 'Hello'
>>> str2 = ' World'
>>> print(str1 + str2)
Hello World

>>> style_char = '-'
>>> style_char * 10
'----------'

>>> word = 'buffalo '
>>> print(word * 8)
buffalo buffalo buffalo buffalo buffalo buffalo buffalo buffalo

# Python v3.6 允许变量使用f-strings进行插入
>>> msg = f'{str1} there'
>>> msg
'Hello there'
#!/usr/bin/python3

"""
这一行是多行注释的一部分

This program shows examples of triple quoted strings
"""

# 把多行字符串赋值给变量
poem = """\
The woods are lovely, dark and deep,
But I have promises to keep,
And miles to go before I sleep,
And miles to go before I sleep.
"""

print(poem, end='')
$ ./triple_quoted_string.py
The woods are lovely, dark and deep,
But I have promises to keep,
And miles to go before I sleep,
And miles to go before I sleep.
$

进一步阅读

常量

来自Python文档 - 常量的释义

>>> bool(2)
True
>>> bool(0)
False
>>> bool('')
False
>>> bool('a')
True

内置操作符

进一步阅读


GitHub

上一篇 下一篇

猜你喜欢

热点阅读