How to combine text and numbers in Python print statement?

There are two common ways to output text and numbers in Python: using string concatenation or formatting strings.

  1. String concatenation:
text = "Hello"
number = 42
print(text + str(number))  # 使用字符串拼接
  1. formatting the string:
text = "Hello"
number = 42
print("{} {}".format(text, number))  # 使用格式化字符串

Please note that in formatted strings, you can use curly braces {} to indicate where you want to insert variables, and pass the variables to the formatted string using the .format() method.

You can output a combination of text and numbers regardless of which method you choose.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds