簡體   English   中英

您如何打印輸入的內容?

[英]How do you print out the input you put in?

我正在編寫一段代碼,詢問用戶的名字,名字,年齡,但是隨后我將其打印出來,但是我不確定如何給出答案。

print ("What is your first name?"),
firstName = input()
print ("What is you last name?"),
secondName = input()
print ("How old are you?")
age = input()

print ("So,  you're %r  %r and you're %r years old."), firstName, secondName, age

您要使用string.format。

您可以這樣使用它:

print ("So, you're {} {} and you're {} years old.".format(firstName, secondName, age))

或者在Python 3.6以上版本中,您可以使用以下速記:

print (f"So, you're {firstName} {secondName} and you're {age} years old.")

采用

print ("So, you're %r  %r and you're %r years old." % (
    firstName, secondName, age))

您可能要考慮將%s用作字符串,將%d用作數字,盡管;-)

Python中的新樣式字符串格式:

print("So, you're {} {} and you're {} years old.".format(firstName, secondName, age))

這是固定的代碼:

firstName = input("What is your first name?")
secondName = input("What is you last name?")
age = input("How old are you?")

print ("So,  you're " + firstName + " " + secondName + " and you're " + age + " years old.")

這很容易理解,因為它僅使用串聯。

有兩種格式化輸出字符串的方式:

  • 舊方法

     print("So, you're %s %s and you're %d years old." % (firstName, secondName, age) 
  • 新方式(首選方式)

     print("So, you're {} {} and you're {} years old.".format(firstName, secondName, age)) 

新方法更加靈活,並提供了一些小巧的便利,例如為占位符提供索引。 您可以在這里找到所有的區別和優點: PyFormat

暫無
暫無

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

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