python 筆記 更多的變量和字符串(string) ——12.22

習題 5: 更多的變量和打印

 

ex5.py

 

my_name = 'Zed A. Shaw'

my_age = 35 # not a lie

my_height = 74 # inches

my_weight = 180 # lbs

my_eyes = 'Blue'

my_teeth = 'White'

my_hair = 'Brown'

 

print "Let's talk about %s." %my_name

print "He's %d inches tall." %my_height

print "He's %d pounds heavy." %my_weight

print "Actually that's not too heavy."

print "He's got %s eyes and %s hair." %(my_eyes, my_hair)

print "His teeth are usually %s depending on the coffee." %my_teeth

 

# this line is tricky, try to get itexactly right

print "If I add %d, %d, and %d I get %d." %(

my_age, my_height, my_weight, my_age + my_height + my_weight)

 

 

 

 

總結:

字符串格式化

格式

描述

%%

百分號標記

%c

字符及其ASCII碼

%s

字符串

%d

有符號整數(十進制)

%u

無符號整數(十進制)

%o

無符號整數(八進制)

%x

無符號整數(十六進制)

%X

無符號整數(十六進制大寫字符)

%e

浮點數字(科學計數法)

%E

浮點數字(科學計數法,用E代替e)

%f

浮點數字(用小數點符號)

%g

浮點數字(根據值的大小採用%e或%f)

%G

浮點數字(類似於%g)

%p

指針(用十六進制打印值的內存地址)

%n

存儲輸出字符的數量放進參數列表的下一個變量中

%r

字符串 (採用repr()的顯示)

 

 

 

自我測試:

 

ex5.1.py

tt =13.555

my_weight = 170 # lib

pounds = 0.453 *my_weight

 

print "you have %6.2f apples" %tt

print "you have %3.2f apples" %tt

print "you have %2.1f apples" %tt

print "you have %1.1f apples" %tt

print "you are %d pounds or %3.3f kg heavy." %(my_weight,pounds)

 

 

 

 

 

習題 6: 字符串(string) 和文本

 

ex6.py

 

x ="There are %d types ofpeople." % 10

binary = "binary"

do_not = "don't"

y ="Those who know %s andthose who %s." % (binary, do_not)

 

print x

print y

 

print "I said: %r." % x

print "I also said: '%s'." % y

 

hilarious = False

joke_evaluation = "Isn't that joke so funny?! %r"

 

print joke_evaluation % hilarious

 

w ="This is the left side of..."

e =" a string with a rightside."

 

print w +e

 

運行結果:

 

 

 

Ex6_1.py  (個人註釋理解)

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

x = "Thereare %d types of people." % 10 #將右邊雙引號的賦值給x,將10格式化輸出(有符號整數)

binary = "binary" #binary賦值給binary

do_not = "don't"  #don't 賦值給 do_not

y = "Thosewho know %s and those who %s." % (binary,do_not) #將右邊雙引號的賦值給y,分別將binary,do_not格式化輸出(字符串)

 

print x

print y

 

print "Isaid: %r." %#此處前面好理解,但是原x的雙引號成了單引號我需要再查查原因。

print "I also said: '%s'." % y

 

hilarious = False

joke_evaluation = "Isn't that joke so funny?! %r"

 

printjoke_evaluation % hilarious  #兩者對比還是有區別的。

print joke_evaluation,hilarious

 

w = "Thisis the left side of ..." #此處後者存在一個空格

e =" a string with a rightside."

 

print w +e

print w ,e


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章