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

如何在Python中打印字符串中递增的int标识符,python,python-3.x,printing,string-concatenation,Python,Python 3.x,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

在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))
我已经尝试了这些链接中提供的解决方案:


您需要将输入转换为整数:

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

在所有的
print
情况下,您都试图将
str
添加到
int
中,错误告诉您,这种形式的隐式转换是不可能的:

'21' +1

TypeErrorTraceback (most recent call last)
<ipython-input-60-3473188b220d> in <module>()
----> 1 '21' +1

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

这里唯一需要注意的是,如果您在输入过程中不提供能够转换为
int
的值,您将得到
ValueError
。在这种情况下,您应该创建一个
while
循环,该循环将
尝试
,并在成功时将输入转换为
int
中断

无需将其更改为
int

>>> age = input("age")
age21
>>> age
21
>>> type(age)
<type 'int'>

输入给您一个字符串。在添加1:
age=int之前,必须将其转换为整数(输入…
即使答案已经被接受,请随意在这里提供答案。我仍然会接受/支持您良好且信息丰富的解决方案。我明白了,我被Python的错误消息误导了。我一直认为它抱怨
int
无法转换为
string
,事实上,它无法将
string
转换为
int
来进行增量操作。另外还有`print(“你已经{}岁了,继续{}”。格式(年龄,年龄+1))为了完整性。为了添加,请尝试使用第二种打印格式,因为这样您就可以正确设置打印语句的格式。更好的做法是,尝试不同的格式,如%f、%s、%r和其他格式。Cheers我仍然需要执行
age=int(输入(“您多大了?”)
首先。在我的例子中,它显示的是
'21'
而不是
21
。在我的例子中,
age
仍然是
str
@user3437460类型,这是Python 2和Python 3之间的区别。在Python 3中:
input
相当于Python 2
raw\u input
-它们返回字符串。然而,在Python 2中,
input
与在Python3中执行
eval(input())
相同。我可以说Python没有像Java那样执行从int到字符串的自动解析吗?因此我总是要执行显式解析?@user3437460是的,在
input
这样的情况下,您必须显式。
>>> age = input("age")
age21
>>> age
21
>>> type(age)
<type 'int'>
print("You are {} years old going on {}".format(age,age+1))