python入门(一)

2019-11-06  本文已影响0人  淡漠不淡漠

数据类型

变量

python 中变量不需要被声明,每个变量在使用前必须赋值,变量赋值以后该变量才会被创建

Numbers

    >>> a, b, c, d = 1, 1.2, True, 1+2j
    >>> print(type(a), type(b), type(c), type(d))
    <class 'int'> <class 'float'> <class 'bool'> <class 'complex'>

String(字符串)

>>> a='name'
>>> print(type(a))
<class 'str'>
>>> a='name\n'
>>> print(a)
name

>>> a=r'name\n'
>>> print(a)
name\n

如果想获取字符串中的某一个字符呢,可以通过下标

 >>> str='hello word'
>>> print(str[0])
h
>>> str='hello word'
>>> print(str[-1])
d

想要获取字符串中的一段呢

  >>> str='hello word'
  >>> print(str[0:5])
  hello

需要注意的是 python字符串不能被修改,会报错

>>> str='hello word'
>>> str[0]='a'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

字符串可以用 + 来拼接

>>> str='hello'+'word'
>>> print(str)
helloword

可以使用 * 运算符重复字符串

>>> str='h'* 3
>>> print(str)
hhh

List (列表)

>>> names=['hello', 1, True, 1.3]
>>> print(name)
['hello', 1, True, 1.3]

获取List中的一个元素

>>> names=['hello', 1, True, 1.3]
>>> print(names[0])
hello

获取List中的几个元素

>>> names=['hello', 1, True, 1.3]
>>> print(names[0:3])
['hello', 1, True]

合并俩个数组呢

>>> n1 = [1, 2, 3]
>>> n1 + [4, 5, 6]
[1, 2, 3, 4, 5, 6]

列表和字符串不一样是可以修改值的

>>> n1 = [1, 2, 3]
>>> n1[0]=4
>>> print(n1)
[4, 2, 3]

Tuple (元组)

>>> a = (1, 1,1, 'name', True)
>>> print(a)
(1, 1, 1, 'name', True)

如何获取元素和获取指定元素

>>> a = (1, 1.1, 'name', True)
>>> print(a[0], a[1:3])
1 (1.1, 'name')

合并元组

>>> a1 = (1, 2, 3)
>>> a1 + (4, 5, 6)
(1, 2, 3, 4, 5, 6)

Sets(集合)

>>> a = {1,1}
>>> print(a)
{1}

使用set()创建

>>> a = set('abc')
>>> print(a)
{'a', 'c', 'b'}

集合可以用来计算

>>> a = set('abcdef')
>>> b = set('abc')
>>> a-b
{'d', 'f', 'e'}
>>> a = set('abcdef')
>>> b = set('abc')
>>> a|b
{'a', 'e', 'c', 'b', 'd', 'f'}
>>> a = set('abcdef')
>>> b = set('abc')
>>> a&b
{'a', 'c', 'b'}
>>> a = set('abcdef')
>>> b = set('abc')
>>> a^b
{'d', 'f', 'e'}

Dictionaries(字典)

>>> dic = {'name':'text', 'age':'18'}
>>> print(dic)
{'name': 'text', 'age': '18'}
>>> dic = {'name':'text', 'age':'18'}
>>> dic['name']
'text'
>>> dic = {'name':'text', 'age':'18'}
>>> del dic['name']
>>> print(dic)
{'age': '18'}
>>> dic['name'] = 'new'
>>> print(dic)
{'age': '18', 'name': 'new'}
>>> dic = {'age': '18', 'name': 'new'}
>>> list(dic.keys())
['age', 'name']
>>> 'name' in dic
True
>>> 'name' not in dic
False
上一篇 下一篇

猜你喜欢

热点阅读