一、常用数据类型
整数类型:
a = 11
b = 99
c = 0b110
d = 0xff
浮点类型:
a = 0.01
b = 0.1234
pi = 3.1415926
字符串:
a = "hello world"
a = 'let\'s go'
a = "let's go"
- 单引号字符串与双引号字符串的区别
'"hello world!" she said'
"\"hello world!\" she said"
效果 figure1.jpg
' 与"单独出现在字符串时,没有区别
若组合出现在字符串时,需要向上述代码一样进行转换。
- 字符串拼接
"let's say" '"hello world!"'
'hello '+'world!'
a = 'hello '
b = 'world!'
print(a+b)
- 长字符串
如果要打印一个非常长的字符串,
print('''This is a very long string. It continues here. And it's not
over yet. "Hello, world!" Still here.''')
print("""This is a very long string. It continues here. And it's not
over yet. "Hello, world!"
Still here.""")
效果:
figure2.jpg
单独 \ 的用法
print("Hello, \
world!")
print(1+2\
+3+4\
+6)
print\
('hello, world')
效果:
figure3.jpg
- 原始字符串
原始字符串即遇到转意符后不发生改变。如
print('hello \n world')
print(r'hello \n world')
效果
figure4.jpg
布尔值:
a = True
b = False
空值:
None
二、常见数据类型
序列:
a = ["张三","李四","王五","赵六","阿帕奇"]
edward = ['Edward Gumby', 42]
john = ['John Smith', 50]
database1 = [edward, john]
database2 = [['Edward Gumby', 42], ['John Smith', 50]]
通用操作-索引
greeting = 'Hello'
greeting[0]
输出:'H'
greeting = 'Hello'
greeting[-1]
输出:'o'
names = ["张三","李四","王五","赵六","阿帕奇"]
print(names[1])
输出:李四
print(names[-2])
输出:赵六
切片
months =['January','February','March','April','May','June','July',\
'August','September','October','November','December']
print(months[2:6])
tag = '<a href="http://www.python.org">Python web site</a>'
print(tag[9:30])
输出:
['March', 'April', 'May', 'June']
'http://www.python.org'
执行切片操作时,你显式或隐式地指定起点和终点,但通常省略另一个参数,即步长。在普通切片中,步长为1。这意味着从一个元素移到下一个元素。当然,步长不能为0,否则无法向前移动,但可以为负数,即从右向左提取元素。
numbers = [1,2,3,4,5,6,8,9,10]
numbers[0:10:2]
输出
[1, 3, 5, 8, 10]
序列相加
print([1, 2, 3] + [4, 5, 6])
print('Hello,' + 'world!')
输出
[1, 2, 3, 4, 5, 6]
Hello world!
序列乘法
'python' * 5
输出
'pythonpythonpythonpythonpython'
[42] * 10
输出:
[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]
序列成员资格
>>> permissions = 'rw' 12
>>> 'w' in permissions
True
>>> 'x' in permissions
False
>>> database = [['albert', '1234'], ['dilbert', '4242'], \
>>> ['smith', '7524'], ['jones', '9843']]
>>> username = 'smith'
>>> code = '7524'
>>> [username,code] in database
True
长度、最小值和最大值
>>> numbers = [100, 34, 678]
>>> len(numbers)
3
>>> max(numbers)
678
>>> min(numbers)
34
>>> max(2, 3)
3
>>> min(9, 3, 2, 5)
2
网友评论