这个问题是关于如何将int转换为字符串的。我是编码新手,我不知道如何将int值转换为str值,因为在python中,我们无法将int值与一个字符串值。所以我们必须将int值转换为string。希望我的问题对自己和以后的编码人员有帮助。
print("Type your age ")
character_age = input()
print("So your age is "+character_age)
print("If your father is 20 years older what will be your fathers age ?")
age_character = int(character_age)
print("Father's age is " +age_character)
答案 0 :(得分:2)
输入:
print("Type your age ")
character_age = input()
print("So your age is "+character_age)
print("If your father is 20 years older what will be your fathers age ?")
age_character = int(character_age)+20 #add 20 with character age
print("Father's age is " + str (age_character )) # convert back into string for print
输出:
Type your age
5
So your age is 5
If your father is 20 years older what will be your fathers age ?
Father's age is 25
答案 1 :(得分:0)
您可以只使用int()
:
x = '10'
int(x)
如果要打印整数变量,则需要使用str()
将其转换回字符串,如最后一行所示:
print("Father's age is " + str(age_character))
答案 2 :(得分:0)
print()
引发TypeError。您无法将string
与int
连接在一起。您需要使用int
函数将string
转换为str
print("Type your age ")
character_age = input()
print("So your age is "+character_age)
print("If your father is 20 years older what will be your fathers age ?")
age_character = int(character_age)
print("Father's age is " +str(age_character))
将print("Father's age is " +age_character)
更改为:
print("Father's age is " +str(age_character))
或
print("Father's age is",age_character)
答案 3 :(得分:0)
您已经使用character_age
构造函数正确地将字符串int
转换为整数,尽管要与另一个字符串连接,您需要将其转换回字符串,并且由于打印出来的消息说父亲的年龄应该比20岁大,因此在转换为字符串之前,您需要添加20岁:
age_character = int(character_age) + 20
print("Father's age is " + str(age_character))
答案 4 :(得分:0)
什么意思是您没有得到想要的结果?
age_character = int(character_age)
age_character变量已将age转换为int。唯一的问题是您尝试打印字符串和整数的组合。您已将其转换为字符串。
print(type(age_character))
print("Father's age is " + str(age_character) )
答案 5 :(得分:0)
由于两种数据类型不同,因此无法使用'+'运算符直接打印整数。您需要将其转换为字符串。尝试以下操作即可。
print("Father's age is " + str(age_character))
其余代码正确
答案 6 :(得分:0)
您可以这样做(无需转换为字符串): 确保您的(character_age必须为整数)
代码: {{打印“所以您的年龄是{character_age}”。format(character_age = character_age)}}
{{打印“父亲的年龄是{age_character}”。format(age_character = age_character)}}
答案 7 :(得分:0)
Python的内置函数int()
可用于此目的。
>>> a = "10"
>>> int(a)
10
但是,只要字符串是可转换的,它就可以工作。
>>> a = "45.2"
>>> int(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '45.2'
>>> b = "eleven"
>>> int(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'eleven'
https://docs.microsoft.com/en-us/aspnet/identity/overview/至int()
文档。