Python基础知识学习-Python数据类型

python教程

共 2145字,需浏览 5分钟

 · 2021-03-06

入门Python,先学一下基础知识吧!跟我一起来复习!

1 Python数据类型

1.1 字符串

在Python中用引号引起来的字符集称之为字符串,比如:'hello'、"my Python"、"2+3"等都是字符串 Python中字符串中使用的引号可以是单引号、双引号跟三引号

print ('hello world!')
hello world!
c = 'It is a "dog"!'
print (c)
It is a "dog"!
c1= "It's a dog!"
print (c1)
It's a dog!
c2 = """hello
world
!"""

print (c2)
hello
world
!
  • 转义字符''

转义字符\可以转义很多字符,比如\n表示换行,\t表示制表符,字符\本身也要转义,所以\ \表示的字符就是\

print ('It\'s a dog!')
print ("hello world!\nhello Python!")
print ('\\\t\\')
It's a dog!
hello world!
hello Python!
\ \

原样输出引号内字符串可以使用在引号前加r

print (r'\\\t\\')
\\\t\\
  • 子字符串及运算
s = 'Python'
print( 'Py'in s)
print( 'py'in s)
True
False

取子字符串有两种方法,使用[]索引或者切片运算法[:],这两个方法使用面非常广

print (s[2])
t
print (s[1:4])
yth
  • 字符串连接与格式化输出
word1 = '"hello"'
word2 = '"world"'
sentence = word1.strip('"') + ' ' + word2.strip('"') + '!'

print( 'The first word is %s, and the second word is %s' %(word1, word2))
print (sentence)
The first word is "hello", and the second word is "world"
hello world!

1.2 整数与浮点数

整数

Python可以处理任意大小的整数,当然包括负整数,在程序中的表示方法和数学上的写法一模一样

i = 7
print (i)
7
7 + 3
10
7 - 3
4
7 * 3
21
7 ** 3
343
7 / 3#Python3之后,整数除法和浮点数除法已经没有差异
2.3333333333333335
7 % 3
1
7//3
2浮点数
7.0 / 3
2.3333333333333335
3.14 * 10 ** 2
314.0

其它表示方法

0b1111
15
0xff
255
1.2e-5
1.2e-05

更多运算

import math

print (math.log(math.e)) # 更多运算可查阅文档
1.0

1.3 布尔值

True
True
False
False
TrueandFalse
False
TrueorFalse
True
notTrue
False
True + False
1
18 >= 6 * 3or'py'in'Python'
True
18 >= 6 * 3and'py'in'Python'
False
18 >= 6 * 3and'Py'in'Python'
True

1.4 日期时间

import time

now = time.strptime('2016-07-20', '%Y-%m-%d')
print (now)
time.struct_time(tm_year=2016, tm_mon=7, tm_mday=20, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=202, tm_isdst=-1)
time.strftime('%Y-%m-%d', now)
'2016-07-20'
import datetime

someDay = datetime.date(1999,2,10)
anotherDay = datetime.date(1999,2,15)
deltaDay = anotherDay - someDay
deltaDay.days
5

还有其他一些datetime格式

  • 查看变量类型
type(None)
NoneType
type(1.0)
float
type(True)
bool
s="NoneType"
type(s)
str
  • 类型转换
str(10086)
'10086'
?float()
float(10086)
10086.0
int('10086')
10086
complex(10086)
(10086+0j)

欢迎大家点赞,留言,转发,转载,感谢大家的相伴与支持


万水千山总是情,点个【在看】行不行

*声明:本文于网络整理,版权归原作者所有,如来源信息有误或侵犯权益,请联系我们删除或授权事宜

浏览 27
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报