在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
最佳答案
您需要将输入转换为 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/