python基本数据类型

多个变量赋值:

a = b = c = 1 a, b, c = 1, 2, "runoob"

python3有六种数据类型:

  • Number(数字)
  • String(字符串)
  • List(列表)
  • Tuple(元组)
  • Sets(集合)
  • Dictionary(字典)

    >>> a, b, c, d = 20, 5.5, True, 4+3j
    >>> print(type(a),type(b),type(c),type(d))
    <class 'int'> <class 'float'> <class 'bool'> <class 'complex'>
    注意:在Python2中是没有布尔型的,它用数字0表示False,用1表示True。到Python3中,把True和False定义成关键字了,但它们的值还是1和0,它们可以和数字相加。

可以使用del语句删除相应的数据类型

>>> del a
>>> print(a)
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    print(a)
NameError: name 'a' is not defined

 

数值运算:

>>> 5 + 4  # 加法
9
>>> 4.3 - 2 # 减法
2.3
>>> 3 * 7  # 乘法
21
>>> 2 / 4  # 除法,得到一个浮点数
0.5
>>> 2 // 4 # 除法,得到一个整数
0
>>> 17 % 3 # 取余 
2
>>> 2 ** 5 # 乘方
32

注意:

  • 1、Python可以同时为多个变量赋值,如a, b = 1, 2。
  • 2、一个变量可以通过赋值指向不同类型的对象。
  • 3、数值的除法(/)总是返回一个浮点数,要获取整数使用//操作符。
  • 4、在混合计算时,Python会把整型转换成为浮点数。
>>> str = 'string'
>>> print(str)
string
>>> print(str[0:-1])
strin
>>> print(str[0])
s
>>> print(str[2:5])
rin
>>> print(str[2:])
ring
>>> print(str*2)
stringstring
>>> print(str+b)
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    print(str+b)
TypeError: Can't convert 'float' object to str implicitly
>>> print(str+'hah')
stringhah
>>> 

Python 使用反斜杠(\)转义特殊字符,如果你不想让反斜杠发生转义,可以在字符串前面添加一个 r,表示原始字符串:

>>> print('c:\no')
c:
o
>>> print(r'c:\no')
c:\no
>>> 
View Code

注意:

  • 1、反斜杠可以用来转义,使用r可以让反斜杠不发生转义。
  • 2、字符串可以用+运算符连接在一起,用*运算符重复。
    >>> word = 'python'
    >>> print(word[0],word[2])
    p t
    >>> print(word[-1])
    n
    >>> print(word[1]='xx')
    SyntaxError: keyword can't be an expression
    >>> print(word[1]='xx')
    SyntaxError: keyword can't be an expression
    >>> word[1]='m'
    Traceback (most recent call last):
      File "<pyshell#32>", line 1, in <module>
        word[1]='m'
    TypeError: 'str' object does not support item assignment
    >>> 

     

  • 3、Python中的字符串有两种索引方式,从左往右以0开始,从右往左以-1开始。
  • 4、Python中的字符串不能改变。

list列表是python中最常见的数据类型

变量[头下标:尾下标]

索引值以 0 为开始值,-1 为从末尾的开始位置。

与Python字符串不一样的是,列表中的元素是可以改变的:

>>> a = [1,2,3,4,5]
>>> a[1] = 7
>>> a
[1, 7, 3, 4, 5]
>>> 
View Code

 

list中内置了许多方法,例如:append()、pop()等等
tuple(元组)

元组(tuple)与列表类似,不同之处在于元组的元素不能修改。元组写在小括号(())里,元素之间用逗号隔开。

元组中的元素类型也可以不相同:

>>> tuple = ('asd', 123 , 2.23 , 'run');tintuple = (123,"asd")
>>> print(tuple)
('asd', 123, 2.23, 'run')
>>> 
>>> print(tuple[1])
123
>>> print(tuple[2:3])
(2.23,)
>>> print(tuple[2:4])
(2.23, 'run')
>>> print(tintuple * 2)
(123, 'asd', 123, 'asd')
>>> print(tintuple + tuple)
(123, 'asd', 'asd', 123, 2.23, 'run')
>>> 

 

 

 

 

 

posted @ 2016-08-08 00:12  上官靖宇  阅读(86)  评论(0编辑  收藏  举报