变量

什么是变量

所谓变量,指的是在程序运行过程中需要用到的中间结果,变量定义后,会占用一块内存开辟的空间地址,通过内存空间确保同一时间的唯一性。

>>> print(id.__doc__)
Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects.
(CPython uses the object's memory address.)

变量的命名规则

1)变量只能是大小写字母、数字和下划线的任意组合,并且开头不能是数字。

2)python中的关键字不能声明为变量使用。

3)变量名描述性要强

>>> 1_level = 1
File "<stdin>", line 1
1_level = 1
^
SyntaxError: invalid syntax >>> level_1 = 1 >>> _level1 = 1 >>> print = 10 >>> print(level_1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

字符编码

ASCII(美国标准信息交换代码)字符编码,用于显示现代英语和西欧语言,最多只能用8位来表示,即1字节,最多2**8 - 1 = 255个符号。

关于中文

1980年设计出了用于存储中文的GB2312,一共收录7445个字符,包括6763个字符和682个其他符号。

1995年设计出了可以收录21886个符号的GBK1.0,2000年GB18030取代GBK1.0的正式国家标准,可以收录27848的汉字。

为了解决不同国家之间经常出现的字符不兼容问题,推出了Unicode(统一码,万国码,单一码),为每种语言的每个字符制定了统一的并且唯一的二进制编码,每个字符统一占用2个字节。

为了解决Unicode在存储英文时多占用1个字节,继续优化出了世界上最流行的UTF8可变长字符编码,英文1个字符还占1个字节,欧洲语言1个字符占2个字节,中文1个字符占3个字节。

python2的解释器在加载.py字节码文件时,使用默认的(ASCII)字符编码,于是不支持中文。

cat hello.py
#!/usr/bin/env python
print '世界,你好' python hello.py
File "hello.py", line 2
SyntaxError: Non-ASCII character '\xe4' in file hello.py on line 2, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

那么,在Python2中,使用中文时需要声明支持中文的字符编码。

cat hello.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
print '世界,你好' python hello.py
世界,你好

python3默认会使用UTF-8字符编码,默认就支持中文。

Python 3.5.2 (default, Dec  2 2016, 17:47:43)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print('世界,你好')
世界,你好

数据类型

数字类型:不加引号的数字

int(整型)

在32位的系统上,整数的位数为32,取值范围从-2**31~2**31-1,即:-2147483648~2147483647

在64为的系统上,整数的位数为64,取值范围从-2**63~2**63-1,即:-9223372036854775808~9223372036854775807

long(长整形)

在python2中使用,如果整数发生溢出,python会自动将整数数值转换为长整形数值,python3中已经不再使用。

float(浮点型)

属于有理数中特定子集的数的数据表示,大约理解为小数,占用8个字节。

数字类型创建

>>> number = 10
>>> type(number)
<class 'int'>
>>> number = int(10)
>>> type(number)
<class 'int'>

布尔值

真或假 True False 1 或 0 ,真代表条件成立。

>>> 12 + 20 > 30
True
>>> 12 + 20 > 35
False

字符串类型:被引号括起来的字符,字符串不能被修改!

字符串创建:可以使用单引号、双引号以及三个单引号或者三个双引号创建,三引号可以换行。

>>> string = 'hello world'
>>> string
'hello world'
>>> string = "hello world"
>>> string
'hello world'
>>> string = '''hello
... world'''
>>> string
'hello\nworld'
>>> string = """hello
... world"""
>>> string
'hello\nworld' 还可以指定字符串类型创建:

 >>> string = str('hello world')
  >>> type(string)
  <class 'str'>
  >>> string
  'hello world'

字符串常用方法:

strip(): 去除字符串两侧的空格,lstrip()去除字符串左侧的空格,rstrip()去除字符串右侧的空格。

>>> name = ' pangjinniu '
>>> print(name.lstrip())
pangjinniu
>>> print(name.rstrip())
pangjinniu
>>> print(name.strip())
pangjinniu

下标:取字符串中的1个字符

>>> name
' pangjinniu ' -> j是字符串的第6个字符,使用下标时从0开始
01234567891011
>>> print(name[5])
j 字符串不能被修改:

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

切片: 取字符串中的多个字符,切片的方法叫顾头不顾尾。

>>> string = "hello world"
012345678910
>>> string[0:5]
'hello'
>>> string[6:]
'world' 切片默认从左往右,-号表示从右往左。
>>> string = ''
>>> string[:]
''
>>> string[::-1]
'' 通过使用步长,可以指定每次取出几个字符后显示第1个字符。
>>> string[::2]
''
>>> string[::-2]
''

拼接: 使用+号,每拼接1次就会开辟一块内存空间,不推荐使用,字符串类型和数字类型不能拼接。

>>> name = 'pangjinniu'
>>> age = ''
>>> print('my name is '+name+' i\'m '+age+' years old.')
my name is pangjinniu i'm 31 years old. 只能是字符串之间完成拼接
>>> age = 31
>>> print('my name is '+name+' i\'m '+age+' years old.')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects 

格式化输出:使用%,可以传入多种数据类型。

>>> name = 'pangjinniu'
>>> age = 31
>>> print('my name is %s , i\'m %s years old.' % (name,age))
my name is pangjinniu , i'm 31 years old. >>> print('my name is {0} , i\'m {1} years old.'.format(name,age))
my name is pangjinniu , i'm 31 years old. >>> print('my name is {_name} , i\'m {_age} years old.'.format(_name=name,_age=age))
my name is pangjinniu , i'm 31 years old.

split():字符串切分并返回列表类型,默认使用空格进行切分

>>> string = 'hello world'
>>> print(string.split())
['hello', 'world']

center():字符串内容居中与填充

>>> string = 'hello world'
>>> len(string)
11 >>> string.center(21,"*")
'*****hello world*****'

count(): 统计字符串里某个字符出现的次数

>>> string = 'hello world'
012345678910
从头到尾:
>>> string.count('o')
2
从字符串位置1到7:
>>> string.count('o',0,7)
1

startswith():判断字符串是否以指定前缀开头

>>> string.startswith('h')
True
>>> string.startswith('w')
False 指定搜索范围
>>> string.startswith('w',6)
True

endswith():判断字符串是否以指定后缀结尾

>>> string = 'hello world'
>>> string.endswith('d')
True
>>> string.endswith('o')
False 指定搜索的范围
>>> string.endswith('o',0,5)
True

find():检查字符串中是否包含子字符串

>>> string
'hello world' 返回下标位置
>>> string.find('hello')
0
>>> string.find('o')
4
>>> string.find('world')
6 没有找到返回-1
>>> string.find('World')
-1

index()与find()相似,只是在没有找到子字符串后会报错

>>> string = 'hello world'
>>> string.index('hello')
0
>>> string.index('world')
6
>>> string.index('World')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found

isalnum():检查字符串是否由字母或数字组成

>>> string = 'pangjinniu'
>>> string.isalnum()
True
>>> string = '31'
>>> string.isalnum()
True
>>> string = 'pangjinniu31'
>>> string.isalnum()
True
>>> string = 'pangjinniu '
>>> string.isalnum()
False

isalpha():字符串只由数字组成

>>> string = '31'
>>> string.isdigit()
True

>>> string = 'pangjinniu31'
>>> string.isdigit()
False

join():将序列中的元素添加指定字符,并生成新的字符串

>>> string = ('','usr','local','bin')
>>> '/'.join(string)
'/usr/local/bin'

replace():将字符创中旧的字符串转换为新的字符串

>>> string = 'hello world'
>>> string.replace('hello','Hello')
'Hello world'

列表常用方法
append():追加成员

>>> name = ['user1','user3','user4']
>>> name.append('user5')
>>> name
['user1', 'user3', 'user4', 'user5']

insert():插入成员到任意位置,通过下标指定。

>>> name.insert(1,'user2')
>>> name
['user1', 'user2', 'user3', 'user4', 'user5']

del:通过下标删除成员

>>> name
['user1', 'user2', 'user3', 'user4', 'user5']
>>> del name[2]
>>> name
['user1', 'user2', 'user4', 'user5']

remove():直接删除列表中的成员

>>> name
['user1', 'user2', 'user4', 'user5']
>>> name.remove('user4')
>>> name
['user1', 'user2', 'user5']

pop():显示列表指定位置的成员并删除,默认显示、删除最后一个成员

>>> name = ['user1','user2','user3','user4','user5']
>>> name.pop()
'user5'
>>> name
['user1', 'user2', 'user3', 'user4']
>>> name.pop(0)
'user1'
>>> name
['user2', 'user3', 'user4'] 使用append(pop())感觉就像是队列
>>> name.append(name.pop())
>>> name
['user2', 'user3', 'user4']

index():查看列表成员的下标位置

>>> name
['user1', 'user2', 'user5']
>>> name.index('user2')
1

 >>> name[name.index('user2')] = 'User2'
  >>> name
  ['User2', 'user3', 'user4']

count():统计列表中成员出现的次数

>>> name
['user1', 'user2', 'user5', 'user2']
>>> name.count('user2')
2

sort():按照ASCII码顺序排序列表

>>> name.sort()
>>> name
['user1', 'user2', 'user2', 'user5']

reverse():反向排序

>>> name.reverse()
>>> name
['user5', 'user2', 'user2', 'user1']

运算:and or not  in not in is is not

name = 'pangjinniu'
age = 29
mac = True and
>>> name == 'pangjinniu' and age < 30
True
>>> name == 'pangjinniu' and age > 30
False or
>>> name == 'pangjinniu' or age > 30
True
>>> name == 'pangjinniu ' or age > 30
False or ... and , or 后面是一个整体条件
>>> mac = False
>>> age > 30 or name == 'pangjinniu' and mac == True
False >>> mac = True
>>> age > 30 or name == 'pangjinniu ' and mac == True
False not
>>> mac = False
>>> age > 30 or name == 'pangjinniu' and not mac == True
True in
>>> names = ['user1','user2','user3']
>>> name = 'user1'
>>> name in names
True not in
>>> name not in names
False is
>>> name is 'user1'
True
>>> name is 'user2'
False is not
False
>>> name is not 'user1'
False
>>> name is not 'user2'
True

python变量与数据类型的更多相关文章

  1. Python变量和数据类型(入门2)

    转载请标明出处: http://www.cnblogs.com/why168888/p/6400809.html 本文出自:[Edwin博客园] Python变量和数据类型 一.整数 int = 20 ...

  2. python入门课程 第3章 Python变量和数据类型

    第3章 Python变量和数据类型3-1 Python中数据类型计算机顾名思义就是可以做数学计算的机器,因此,计算机程序理所当然地可以处理各种数值.但是,计算机能处理的远不止数值,还可以处理文本.图形 ...

  3. Python变量、数据类型6

    1.Python变量 变量,即代表某个value的名字. 变量的值存储在内存中,这意味着在创建变量时会在内存中开辟一个空间. !!!即值并没有保存在变量中,它们保存在计算机内存的深处,被变量引用.所以 ...

  4. 【python系列】--Python变量和数据类型

    python数据类型 一.整数 Python可以处理任意大小的整数,当然包括负整数,在Python程序中,整数的表示方法和数学上的写法一模一样,例如:1,100,-8080,0,等等. 计算机由于使用 ...

  5. Python 变量和数据类型

    变量的定义与赋值 Python 是动态语言,我们不需要为变量指定数据类型,只需要输入变量名和值就行了.每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建. 此外 Python 允许你同时为多个变 ...

  6. Python变量和数据类型

    十六进制用0x前缀和0-9 a-f表示   字符串是以''或""括起来的任意文本   一个布尔值只有True和False两种值   布尔值可以用and or not运算   空值是 ...

  7. Python变量及数据类型

    所有编程语言几乎都会有 ’ 变量‘ ,如 a = 2,用一个a变量指代数字2,在Python中,一切皆对象,因此在变量赋值的时候实际上是在内存中开辟了一块存储变量内容的内存空间对象. 对象可以指定不同 ...

  8. Python 变量与数据类型

    1.变量命名规则: 变量名只能是字母,数字和下划线的任意组合 变量名第一个字符不能是数字 变量名区分大小写,大小写字母被认为是两个不同的字符 特殊关键字不能命名为变量名 2.数值的运算 print ( ...

  9. Python变量和数据类型,类型转换

    a.变量的定义 把数据分别用一个简单的名字代表,方便在接下来的程序中引用. 变量就是代表某个数据(值)的名称. 变量就是用来存储数据的,将不同的数据类型存储到内存   b.变量的赋值 变量名= 初始值 ...

随机推荐

  1. a5站长论坛和s8站长论坛-网上兼职做任务赚钱的两大网站

     1.什么是做任务赚钱? 简而言之,就是你做别人不在行而你在行的技术 ,如 图片美化 网站建设 网站修改 网站推广等网络业务. 2.任务赚钱有什么特点? 完全免费,你付出的是技术和时间,完全免费,不过 ...

  2. Kafka分布式集群搭建

    环境说明 kafka自0.9之后增加了connector的特性.本文主要是搭建一个分布式的kafka connector和broker. 本文用了三台机器进行部署,使用centos 6.6. host ...

  3. 理解Javascript的状态容器Redux

    Redux要解决什么问题? 随着 JavaScript 单页应用开发日趋复杂,JavaScript 需要管理比任何时候都要多的 state (状态). 这些 state 可能包括服务器响应.缓存数据. ...

  4. 转载 C#文件上传

     一.分析 本次博客,主要解决文件上传等一系列问题,将从两方面来论述,即1G以内文件和1G以上文件. 对于上传1G以内的文件,可以采用基本的三种上传方法:用Web控件FileUpload.html控件 ...

  5. tabindex属性

    1. tabindex的用法: 可以设置tab键在控件中的移动顺序. 以下元素支持tabindex属性:<a> <input> <textarea> <are ...

  6. 运行Google 官方zxing二维码扫描器

    首先,要去下载Zxing的源码,由于Zxing 的服务内容比较广,我们先把所有的源码都下载下来,使用的时候根据需要加载. 或者从开源中国下载https://www.oschina.net/questi ...

  7. 使用Redis的Java客户端Jedis

    转载自:http://aofengblog.blog.163.com/blog/static/631702120147298317919/ 前一篇文章<Redis命令指南>讲解了通过命令行 ...

  8. windows环境自动获取SVN仓库当前版本

    如果我们的软件能够自动引入SVN修订号(仓库版本号),那么我们开发软件的时候就能快速定位bug出自哪个SVN版本.那么如何让软件直接自动生成并引用SVN版本号呢? 我们可以使用SVN info命令,在 ...

  9. python爬虫框架scrapy初试(二点一)

    功能:爬取某网站部分新闻列表和对应的详细内容. 列表页面http://www.zaobao.com/special/report/politic/fincrisis 实现代码: import scra ...

  10. arm指令集

    http://blog.chinaunix.net/uid-20769502-id-112445.html