簡體   English   中英

如何在 Python 的同一行上打印變量和字符串?

[英]How can I print variable and string on same line in Python?

我正在使用 python 來計算如果每 7 秒有一個孩子出生,那么 5 年內會有多少個孩子出生。 問題在我的最后一行。 當我在它的任一側打印文本時,如何讓變量工作?

這是我的代碼:

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"

使用,在打印時分隔字符串和變量:

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

,在 print 函數中用一個空格分隔項目:

>>> print("foo", "bar", "spam")
foo bar spam

或者更好地使用字符串格式

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

字符串格式要強大得多,並且還允許您執行其他一些操作,例如填充、填充、對齊、寬度、設置精度等。

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

演示:

>>> 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

Python 是一種非常通用的語言。 您可以通過不同的方法打印變量。 我列出了以下五種方法。 您可以根據自己的方便使用它們。

例子:

a = 1
b = 'ball'

方法一:

print('I have %d %s' % (a, b))

方法二:

print('I have', a, b)

方法三:

print('I have {} {}'.format(a, b))

方法四:

print('I have ' + str(a) + ' ' + b)

方法五:

print(f'I have {a} {b}')

輸出將是:

I have 1 ball

還有兩個

第一個

>>> births = str(5)
>>> print("there are " + births + " births.")
there are 5 births.

添加字符串時,它們會連接起來。

第二個

此外,字符串的format (Python 2.6 和更新版本)方法可能是標准方法:

>>> births = str(5)
>>>
>>> print("there are {} births.".format(births))
there are 5 births.

format方法也可用於列表

>>> format_list = ['five', 'three']
>>> # * unpacks the list:
>>> print("there are {} births and {} deaths".format(*format_list))  
there are five births and three deaths

或字典

>>> format_dictionary = {'births': 'five', 'deaths': 'three'}
>>> # ** unpacks the dictionary
>>> print("there are {births} births, and {deaths} deaths".format(**format_dictionary))
there are five births, and three deaths

如果你想使用 python 3,這很簡單:

print("If there was a birth every 7 second, there would be %d births." % (births))

從 python 3.6 開始,您可以使用文字字符串插值。

births = 5.25487
>>> print(f'If there was a birth every 7 seconds, there would be: {births:.2f} births')
If there was a birth every 7 seconds, there would be: 5.25 births

您可以使用f-string.format()方法

使用 f 字符串

print(f'If there was a birth every 7 seconds, there would be: {births} births')

使用 .format()

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

您可以使用格式字符串:

print "There are %d births" % (births,)

或者在這個簡單的情況下:

print "There are ", births, "births"

如果您使用的是 python 3.6 或最新版本,f-string 是最好且簡單的

print(f"{your_varaible_name}")

在當前的 python 版本上,您必須使用括號,如下所示:

print ("If there was a birth every 7 seconds", X)

您將首先創建一個變量:例如:D = 1。然后執行此操作,但將字符串替換為您想要的任何內容:

D = 1
print("Here is a number!:",D)

您可以使用字符串格式來執行此操作:

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

或者你可以給print多個參數,它會自動用空格分隔它們:

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

使用字符串格式

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

如果你做一個玩具項目使用:

print('If there was a birth every 7 seconds, there would be:' births'births) 

或者

print('If there was a birth every 7 seconds, there would be: %d births' %(births))
# Will replace %d with births

我將您的腳本復制並粘貼到 .py 文件中。 我使用 Python 2.7.10 按原樣運行它並收到相同的語法錯誤。 我還嘗試了 Python 3.5 中的腳本並收到以下輸出:

File "print_strings_on_same_line.py", line 16
print fiveYears
              ^
SyntaxError: Missing parentheses in call to 'print'

然后,我修改了打印出生人數的最后一行,如下所示:

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: " + str(births) + " births"

輸出是(Python 2.7.10):

157680000
If there was a birth every 7 seconds, there would be: 22525714 births

我希望這有幫助。

只需在兩者之間使用 ,(逗號)。

請參閱此代碼以更好地理解:

# Weight converter pounds to kg

weight_lbs = input("Enter your weight in pounds: ")

weight_kg = 0.45 * int(weight_lbs)

print("You are ", weight_kg, " kg")

使用字符串格式:

birth = 5.25487
print(f'''
{birth} 
''')

從 Python-3.8 開始,您可以使用帶有變量打印的 f 字符串!

age = 19
vitality = 17
charisma = 16
name = "Alice"
print(f"{name=}, {age=}, {vitality=}, {charisma=}")
# name='Alice', age=19, vitality=17, charisma=16
  • 命名錯誤在這里幾乎是不可能的,如果你添加、重命名或刪除一個變量,你的調試打印將保持正確
  • 調試行非常簡潔
  • 不用擔心 alignment。 第四論點是charisma還是vitality 好吧,你不在乎,無論如何都是正確的。

略有不同:使用 Python 3 並在同一行中打印多個變量:

print("~~Create new DB:",argv[5],"; with user:",argv[3],"; and Password:",argv[4]," ~~")

蟒蛇3

最好使用格式選項

user_name=input("Enter your name : )

points = 10

print ("Hello, {} your point is {} : ".format(user_name,points)

或將輸入聲明為字符串並使用

user_name=str(input("Enter your name : ))

points = 10

print("Hello, "+user_name+" your point is " +str(points))

如果在字符串和變量之間使用逗號,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM