python - 如何在 Python 中打印字符串中递增的 int 标识符

标签 python printing string-concatenation

在Java中,如果我想打印一个递增的int变量,我可以这样做:

int age = scn.nextInt();
System.out.println("You are " + age + " years old going on " + (age+1));

输出:

21
You are 21 years old going on 22

在 Python 中可以做同样的事情吗?

我尝试了以下方法,但没有一个起作用。

age = input("How old are you?")
print("You are " + age + " years old going on " + str(age+1))
print("You are " + age + " years old going on {}".format(age+1))
print("You are " , age , " years old going on " , str(age+1))
print("You are %d years old going on %d" %(age, age+1))
print("You are " + str(age) + " years old going on " + str(age+1))

我已经尝试过这些链接中提供的解决方案:

Print Combining Strings and Numbers

Concatenating string and integer in python

Converting integer to string in Python?

TypeError: Can't convert 'int' object to str implicitly

最佳答案

您需要将输入转换为 int :

>>> age = int(input("How old are you?"))

然后进行以下工作:

print("You are " , age , " years old going on " , str(age+1))
print("You are %d years old going on %d" %(age, age+1))
print("You are " + str(age) + " years old going on " + str(age+1))

关于python - 如何在 Python 中打印字符串中递增的 int 标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38870566/

相关文章:

python - 如何为函数 Python 中的局部变量赋值?

python - 如何优化推理脚本以获得更快的分类器预测?

c# - 程序打印到斑马打印机 ZPL?或替代品?

r - R中的操作重载

c# - 奇怪的空字符串连接行为

python - 测试之间的 django 数据

python - 选择 pandas groupby 数据框的子集,其中多个键具有值

html - 如何使用 HTML 打印正方形(在打印机上)?

c - EOF 读取最后一行两次

c++ - 连接 const_string 的