Table of Contents
一、整数
二、浮点数
三、字符串
四、布尔值
五、空值
六、列表
七、字典
八、元祖
九、定义字符串
十、Unicode字符串
十一、数字类型转换
Home Backend Development Python Tutorial Detailed introduction to Python variables and data types

Detailed introduction to Python variables and data types

Mar 27, 2017 pm 03:49 PM

Python变量和数据类型

一、整数

int = 20
print int
print 45678 + 0x12fd2
Copy after login

二、浮点数

float = 2.3
print float
Copy after login

三、字符串

a、使用单引号(')
用单引号括起来表示字符串,例如:
str = 'this is string'
print str

b、使用双引号(")
双引号中的字符串与单引号中的字符串用法完全相同,例如:
str = "this is string";
print str

c、使用三引号(''')
利用三引号,表示多行的字符串,可以在三引号中自由的使用单引号和双引号,例如:
str = '''this is string
this is pythod string
this is string'''
print str
Copy after login

四、布尔值

and:与运算,只有所有都为True,and运算结果才是True。
or:或运算,只要其中有一个为True,or运算结果就是True。
not:非运算,它是一个单目运算符,把True变成False,False 变成True。

bool = False
print bool
bool = True
print bool
Copy after login

五、空值

空值是Python里一个特殊的值,用None表示。
None不能理解为0,因为0是有意义的,而None是一个特殊的空值。
Copy after login

六、列表

# -*- coding:utf-8 -*-

lst = ['A', 'B', 1996, 2017]
nums = [1, 3, 5, 7, 8, 13, 20]

# 访问列表中的值
print "nums[0]:", nums[0]  # 1
print "nums[2:5]:", nums[2:5]  # [5, 7, 8]
print "nums[1:]:", nums[1:]  # [3, 5, 7, 8, 13, 20]
print "nums[:-3]:", nums[:-3]  # [1, 3, 5, 7]
print "nums[:]:", nums[:]  # [1, 3, 5, 7, 8, 13, 20]

# 更新列表
nums[0] = "ljq"
print nums[0]

# 删除列表元素
del nums[0]
'''nums[:]: [3, 5, 7, 8, 13, 20]'''
print "nums[:]:", nums[:]

# 列表脚本操作符
print len([1, 2, 3])  # 3
print [1, 2, 3] + [4, 5, 6]  # [1, 2, 3, 4, 5, 6]
print ['Hi!'] * 4  # ['Hi!', 'Hi!', 'Hi!', 'Hi!']
print 3 in [1, 2, 3]  # True
for x in [1, 2, 3]:
    print x,  # 1 2 3

# 列表截取
L = ['spam', 'Spam', 'SPAM!']
print L[2]  # 'SPAM!'
print L[-2]  # 'Spam'
print L[1:]  # ['Spam', 'SPAM!']

# 列表函数&方法
lst.append('append')  # 在列表末尾添加新的对象
lst.insert(2, 'insert')  # 将对象插入列表
lst.remove(1996)  # 移除列表中某个值的第一个匹配项
lst.reverse()  # 反向列表中元素,倒转
print lst.sort()  # 对原列表进行排序
print lst.pop(1)  # 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
print lst
print lst.count('obj')  # 统计某个元素在列表中出现的次数
lst.index('append')  # 从列表中找出某个值第一个匹配项的索引位置,索引从0开始
lst.extend(lst)  # 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
print 'End:', lst
Copy after login

七、字典

字典(dictionary)是除列表之外python中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。

# -*- coding:utf-8 -*-

dit = {'name': 'Zara', 'age': 7, 'class': 'First'}
dict1 = {'abc': 456}
dict2 = {'abc': 123, 98.6: 37}
seq = ('name', 'age', 'sex')
# 访问字典里的值
print "dit['name']: ", dit['name']
print "dit['age']: ", dit['age']

# 修改字典
dit["age"] = 27  # 修改已有键的值
dit["school"] = "wutong"  # 增加新的键/值对
print "dict['age']: ", dit['age']
print "dict['school']: ", dit['school']

# 删除字典
del dit['name']  # 删除键是'name'的条目
dit.clear()  # 清空词典所有条目
del dit  # 删除词典

dit = {'name': 'Zara', 'age': 7, 'class': 'First'}

# 字典内置函数&方法
cmp(dict1, dict2)  # 比较两个字典元素。
len(dit)  # 计算字典元素个数,即键的总数。
str(dit)  # 输出字典可打印的字符串表示。
type(dit)  # 返回输入的变量类型,如果变量是字典就返回字典类型。
dit.copy()  # 返回一个字典的浅复制
dit.fromkeys(seq)  # 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
dit.get(dit['name'])  # 返回指定键的值,如果值不在字典中返回default值
dit.has_key('class')  # 如果键在字典dict里返回true,否则返回false
dit.items()  # 以列表返回可遍历的(键, 值) 元组数组
dit.keys()  # 以列表返回一个字典所有的键
dit.setdefault('subject', 'Python')  # 和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default
dit.update(dict2)  # 把字典dict2的键/值对更新到dict里
dit.values()  # 以列表返回字典中的所有值
dit.clear()  # 删除字典内所有元素
Copy after login

八、元祖

Python的元组(tuple)与列表类似,不同之处在于元组的元素不能修改;元组使用小括号(),列表使用方括号[];元组创建很简单,只需要在括号中添加元素,并使用逗号(,)隔开即可.

# -*- coding:utf-8 -*-

tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5)
tup3 = "a", "b", "c", "d"

# 访问元组
print "tup1[0]: ", tup1[0]  # physics
print "tup1[1:3]: ", tup1[1:3]  # ('chemistry', 1997)

# 修改元组
tup4 = tup1 + tup2
print tup4  # (12, 34.56, 'abc', 'xyz')

# 删除元组
tup = ('tup3', 'tup', 1997, 2000)
print tup
del tup

# 元组索引&截取
L = ('spam', 'Spam', 'SPAM!')
print L[0]  # spam
print L[1]  # Spam
print L[2]  # 'SPAM!'
print L[-2]  # 'Spam'
print L[1:]  # ['Spam', 'SPAM!']

# 元组内置函数
print cmp(tup3, tup2)  # 比较两个元组元素。
len(tup3)  # 计算元组元素个数。
max(tup3)  # 返回元组中元素最大值。
min(tup3)  # 返回元组中元素最小值。
L = [1, 2, 3, 4]
print L
print tuple(L)  # 将列表转换为元组。
Copy after login

九、定义字符串

\n 表示换行
\t 表示一个制表符
\\ 表示 \ 字符本身
Copy after login

十、Unicode字符串

Python默认编码ASCII编码

# -*- coding: utf-8 -*-
Copy after login

十一、数字类型转换

int(x [,base]) 将x转换为一个整数 
float(x ) 将x转换到一个浮点数 
complex(real [,imag]) 创建一个复数 
str(x) 将对象x转换为字符串 
repr(x) 将对象x转换为表达式字符串 
eval(str) 用来计算在字符串中的有效Python表达式,并返回一个对象 
tuple(s) 将序列s转换为一个元组 
list(s) 将序列s转换为一个列表 
chr(x) 将一个整数转换为一个字符 
unichr(x) 将一个整数转换为Unicode字符 
ord(x) 将一个字符转换为它的整数值 
hex(x) 将一个整数转换为一个十六进制字符串 
oct(x) 将一个整数转换为一个八进制字符串
Copy after login

The above is the detailed content of Detailed introduction to Python variables and data types. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles