简体   繁体   English

在输入中使用计算和字符串。 (Python 2.7)

[英]Using a calculation and a string in an input. (Python 2.7)

I'm having this annoying problem in Python 2.7, it won't let me do this 我在python 2.7中遇到这个烦人的问题,它不会让我这样做

numbers = raw_input(numbers + 1 + ': ')

I want it to print out 'numbers + 1' as a number in the console but.. It comes up with this error message: 我希望它在控制台中打印出“数字+ 1”作为数字,但是..它带有以下错误消息:

Traceback (most recent call last):
  File "F:/Python/Conversation", line 25, in <module>
    numbers = raw_input(numbers + 1 + ': ')
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Is there a solution or just another thing that I can use instead of this? 有没有解决方案,或者我可以代替它使用? Thanks in advance! 提前致谢!

You need to put + and numbers inside a single/double quote; 您需要在单/双引号中加上+numbers or else, it will be treated as a string concatenation. 否则,它将被视为字符串连接。 You got the error because you tried to concatenate/add numbers with 1 . 您收到错误消息是因为您尝试将numbers1连接/相加。

So, you need to cast 1 to a string, using str( ) . 因此,您需要使用str()1 强制转换为字符串。 Then, concatenate it with 'numbers + ' and ': '. 然后,将其与'numbers + '': ”连接。 Like so: 像这样:

>>> numbers = raw_input('numbers + ' + str(1) + ': ')
numbers + 1: 

However , If you want to replace numbers with number: 但是 ,如果要用numbers替换numbers

>>> numbers = 3
>>> numbers = raw_input(str(numbers + 1) + ': ')
4:

It works because you add the numbers 's value with 1 first. 之所以有效,是因为您首先将numbers的值加1 Then, cast the result to string later. 然后,将结果转换为字符串。

As the error message points out, you cannot add a number and a string. 错误消息指出,您不能添加数字和字符串。 You can add two strings, so try this: 可以添加两个字符串,因此请尝试以下操作:

raw_input( str(numbers+1) + ':' )

You need to turn the 1 int value into a string: 您需要将1 int值转换为字符串:

numbers = raw_input(numbers + str(1) + ': ')

Alternatively, use string formatting: 或者,使用字符串格式:

numbers = raw_input('{}{}: '.format(numbers, 1))

Or perhaps you wanted to turn numbers into an int first, then the result into a string: 或者,您可能想先将numbers转换为int ,然后将结果转换为字符串:

sum = int(numbers) + 1
numbers = raw_input(str(sum) + ': ')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM