Python基礎知識學習-Python數據類型

入門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)
歡迎大家點贊,留言,轉發(fā),轉載,感謝大家的相伴與支持
萬水千山總是情,點個【在看】行不行
*聲明:本文于網絡整理,版權歸原作者所有,如來源信息有誤或侵犯權益,請聯系我們刪除或授權事宜
評論
圖片
表情
