Python格式縮進(jìn)一般為四個空格,代碼段不能復(fù)制粘貼,否則空格將失效
#print absoute value of an integer
a = 100
if a >= 0:
print (a)
else:
print (-a)
100
a = 'ABC'
b = a
a = 'XYZ'
print (b)
print (a)
ABC
XYZ
除法取浮點數(shù)
10/3
3.3333333333333335
除法取整數(shù)
3.0
10//3
3
取余數(shù)
10%3
1
r---不轉(zhuǎn)義,\n換行,''''''---換行時可以使用
n = 123
f = 456.789
s1 = 'Hello, world'
s2 = 'Hello, \'Adam\''
s3 = r'Hello, "Bart"'
s4 = 'Hello\n"Bart"'
s5 = r'''Hello,
isa!,
sss'''
print (n)
print (f)
print (s1)
print (s2)
print (s3)
print (s4)
print (s5)
123
456.789
Hello, world
Hello, 'Adam'
Hello, "Bart"
Hello
"Bart"
Hello,
isa!,
sss
字符編碼轉(zhuǎn)換,字符轉(zhuǎn)換編碼ord(),編碼轉(zhuǎn)換字符chr()
ord('a')
97
ord('A')
65
chr(97)
'a'
chr(65)
'A'
ord('白')
30333
ord('云')
20113
ord('飛')
39134
chr(30333)
'白'
'ABC' .encode('ascii')
b'ABC'
'中文' .encode('utf8')
b'\xe4\xb8\xad\xe6\x96\x87'
'中文' .encode('GB2312')
b'\xd6\xd0\xce\xc4'
'中文' .encode('ascii')
---------------------------------------------------------------------------
UnicodeEncodeError Traceback (most recent call last)
<ipython-input-42-be6ab0d213fc> in <module>()
----> 1 '中文' .encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
- UTF-8格式保存輸出
#/usr/bin/env
#-*- coding: utf-8 -*-
print ('中文測試')
中文測試
格式化輸出字符串
'hello,%s' %'world'
'hello,world'
'Hi,%s,you have $%d.' %('lili',1000)
'Hi,lili,you have $1000.'
%使用來格式化字符串的,%s表示用字符串替換,%d表示用整數(shù)替換,%f表示替換浮點數(shù),%x表示替換十六進(jìn)制數(shù)
其中格式化整數(shù)和浮點數(shù)可以指定是否補(bǔ)0和整數(shù)、浮點數(shù)的位數(shù)
print ('%2d-%02d' % (3,1))
3-01
print ('%.2f' % 3.1425679)
3.14
%s可以把任何的數(shù)據(jù)類型轉(zhuǎn)換為字符串類型,不會使用以上的類型替換,可以使用%s來替換
'Age: %s, Gender %s' %(25,'True')
'Age: 25, Gender True'
- %為普通字符時,需要轉(zhuǎn)義,需要用%%來代替
'growth rate %d%%' % 7
'growth rate 7%'
另一種格式化方法
format()
使用format()方法,它會用傳入的參數(shù)一次替換字符串內(nèi)的占位符{0}、{1}......,這種方法比%麻煩的多
'hello,{0},成績提升了{(lán)1:.1f}%'.format('小明',17.234)
'hello,小明,成績提升了17.2%'
小明的成績從去年的72分提升到了今年的85分,請計算小明成績提升的百分點,并用字符串格式化顯示出'xx.x%',只保留小數(shù)點后1位:
s1=72
s2=85
print ('%.2f'%((s2-s1)/72))
0.18
s1=72
s2=85
r=(s2-s1)/72
print (r)
print ('%.2f'%r)
0.18055555555555555
0.18