首页 > 代码库 > 一入Python深似海--print

一入Python深似海--print

先给大家来个干货^~^,学习Python的一个好网站,http://learnpythonthehardway.org/book/


经典例子

下面是几个老经典的例子喽,刚接触Python的可以敲一敲,看看结果喽!

my_name='Zed A. Shaw'
my_age=35#not a lie
my_height=74#inches
my_weight=180#1bs
my_eyes='Blue'
my_teeth='white'
my_hair='Brown'
print my_name
print "Let's talk about %r" %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 it exactly right
print "If I add %d, %d,and %r I get %d."%(my_age,my_height,my_weight,my_age+my_height+my_weight)

x="There are %d types of people."%10
binary="binary"
do_not="don't"
y="Those who know %s and those 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 right side"

print w+e

print "Mary had a little lamb."
print "Its fleece was white as %s."%'snow'
print "Its fleece was white as %r."%'snow'
print "And everywhere that Mary went."
print "."*10 #output . 10 times

end1="c"
end2="h"
end3="e"
end4="e"
end5="s"
end6="e"
#watch that comma at the end.
print end1+end2+end3,
print end4+end5+end6

formatter="%r %r %r %r"

print formatter %(1,2,3,4)
print formatter %("one","two","three","four")
print formatter %(True,False,False,True)
print formatter %(formatter,formatter,formatter,formatter)
print formatter %(
	"I had this thing.",
	"That you could type up right.",
	"But it didn't sing.",
	"So I said goodnight."
	)

days="Mon Tue Wed Thu Fri Sat Sun"
months="Jan\nFeb\nMar\nApr\nMay\nJun\nAug"

print "Here are the days:",days
print "Here are the months:",months
print "Here are the months: %r"%months
#That's how %r formatting works; 
#it prints it the way you wrote it (or close to it). It's the "raw" format for debugging.
print """
There's something going on here.
whith the three double-quotes.
we'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
"""

tabby_cat="\tI'm stabbed in."
persian_cat="I'm split\non a line."
backslash_cat="I'm \\ a \\ cat."

fat_fat="""
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""

print tabby_cat
print persian_cat
print backslash_cat
print fat_fat


%r与%s的区别

我的总结是这么个点:  %r与%s的区别

That‘s how %r formatting works; it prints it the way you wrote it (or close to it). It‘s the "raw" format for debugging.

Always remember this: %r is for debugging, %s is for displaying.