Python 为什么乘法会多次重复这个数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12733184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:44:28  来源:igfitidea点击:

Why does multiplication repeats the number several times?

pythonstringmultiplying

提问by user1704332

I don't know how to multiply in Python.

我不知道如何在 Python 中进行乘法运算。

If I do this:

如果我这样做:

price = 1 * 9

It will appear like this:

它会是这样的:

111111111

And the answer needs to be 9(1x9=9)

答案必须是91x9=9

How can I make it multiply correctly?

我怎样才能让它正确繁殖?

回答by dm03514

Use integers instead of strings.

使用整数而不是字符串。

make sure to cast your string to ints

确保将您的字符串转换为整数

price = int('1') * 9

price = int('1') * 9

The actual example code you posted will return 9not 111111111

您发布的实际例子的代码将返回9111111111

回答by ronak

In [58]: price = 1 *9
In [59]: price
Out[59]: 9

回答by Rohit Jain

Only when you multiply integer with a string, you will get repetitive string..

只有当您将整数与字符串相乘时,您才会得到重复的字符串..

You can use int()factory method to create integer out of string form of integer..

您可以使用int()工厂方法从整数的字符串形式创建整数..

>>> int('1') * int('9')
9
>>> 
>>> '1' * 9
'111111111'
>>>
>>> 1 * 9
9
>>> 
>>> 1 * '9'
'9'
  • If both operand is int, you will get multiplication of them as int.
  • If first operand is string, and second is int.. Your string will be repeated that many times, as the value in your integer 2nd operand.
  • If first operand is integer, and second is string, then you will get multiplication of both numbers in string form..
  • 如果两个操作数都是 int,您将得到它们的乘积为 int。
  • 如果第一个操作数是字符串,第二个是 int.. 您的字符串将重复多次,作为整数第二个操作数中的值。
  • 如果第一个操作数是整数,第二个是 string,那么您将获得字符串形式的两个数字的乘法。

回答by dkamins

It's the difference between strings and integers. See:

这是字符串和整数之间的区别。看:

>>> "1" * 9
'111111111'

>>> 1 * 9
9

回答by Joseph Victor Zammit

Should work:

应该管用:

In [1]: price = 1*9

In [2]: price
Out[2]: 9

回答by larsga

I think you're confused about types here. You'll only get that result if you're multiplying a string. Start the interpreter and try this:

我认为你对这里的类型感到困惑。如果您将字符串相乘,您只会得到那个结果。启动解释器并尝试以下操作:

>>> print "1" * 9
111111111
>>> print 1 * 9
9
>>> print int("1") * 9
9

So make sure the first operand is an integer (and not a string), and it will work.

所以确保第一个操作数是一个整数(而不是字符串),它会起作用。

回答by Chimp

You cannot multiply an integer by a string. To be sure, you could try using the int (short for integer which means whole number) command, like this for example -

不能将整数乘以字符串。可以肯定的是,您可以尝试使用 int(整数的缩写,表示整数)命令,例如 -

firstNumber = int(9)
secondNumber = int(1)
answer = (firstNumber*secondNumber)

Hope that helped :)

希望有所帮助:)