Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

python - 如何在Python中的同一行上打印变量和字符串?(How can I print variable and string on same line in Python?)

I am using python to work out how many children would be born in 5 years if a child was born every 7 seconds.

(如果孩子每7秒钟出生一次,我正在使用python来计算出5年内会有多少孩子出生。)

The problem is on my last line.

(问题出在我的最后一行。)

How do I get a variable to work when I'm printing text either side of it?

(当我在其两侧打印文本时,如何使变量起作用?)

Here is my code:

(这是我的代码:)

currentPop = 312032486
oneYear = 365
hours = 24
minutes = 60
seconds = 60

# seconds in a single day
secondsInDay = hours * minutes * seconds

# seconds in a year
secondsInYear = secondsInDay * oneYear

fiveYears = secondsInYear * 5

#Seconds in 5 years
print fiveYears

# fiveYears in seconds, divided by 7 seconds
births = fiveYears // 7

print "If there was a birth every 7 seconds, there would be: " births "births"
  ask by Bob Uni translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use , to separate strings and variables while printing:

(使用,在打印时分隔字符串和变量:)

print "If there was a birth every 7 seconds, there would be: ",births,"births"

, in print statement separtes the items by a single space:

(,在print语句中,用单个空格分隔项目:)

>>> print "foo","bar","spam"
foo bar spam

or better use string formatting :

(或更好地使用字符串格式 :)

print "If there was a birth every 7 seconds, there would be: {} births".format(births)

String formatting is much more powerful and allows you to do some other things as well, like : padding, fill, alignment,width, set precision etc

(字符串格式化功能更强大,并允许您执行其他一些操作,例如:填充,填充,对齐,宽度,设置精度等)

>>> print "{:d} {:03d} {:>20f}".format(1,2,1.1)
1 002             1.100000
  ^^^
  0's padded to 2

Demo:

(演示:)

>>> births = 4
>>> print "If there was a birth every 7 seconds, there would be: ",births,"births"
If there was a birth every 7 seconds, there would be:  4 births

#formatting
>>> print "If there was a birth every 7 seconds, there would be: {} births".format(births)
If there was a birth every 7 seconds, there would be: 4 births

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...