简体   繁体   English

如何在Python中将字符串转换为整数

[英]How do you convert a string to an integer in Python

""" A trimorphic number is a number whose cube ends in the number itself. “”“三态数是一个数字,其立方体以数字本身结尾。

For example: 例如:

Input: 4
Output: true (4^3 is 64, which ends in 4)

Input: 24
Output: true (24^3 = 13824)

Input: 249
Output: true (249^3 = 15438249)

Write a program to check if the user input is a trimorphic number or not. 编写程序以检查用户输入是否为三态数。 """ “””

num = int(input("Enter a number:"))
print(num)

num_cube = pow(num, 3)
str(num_cube)
print(num_cube[len(num_cube) - 1:] == num)

I tried running the code and I got a TypeError at line 22 (the last line) even though I converted the variable num_cube to a string in order to slice it. 我尝试运行代码,尽管将变量num_cube转换为字符串以对其进行切片,但在第22行(​​最后一行)却遇到TypeError。 Why does it not work? 为什么不起作用?

str(num_cube) is not assigned, so you are converting it but still using num_cube which is an int, hence the TypeError . str(num_cube)未分配,因此您正在转换它,但仍使用num_cube它是一个整数),因此使用TypeError Also, you need to compare it to another string, not to to num which is another integer: 另外,你需要将其与另一个字符串,不向num这是另一个整数:

print(str(num_cube)[-3:] == str(num))

You should use the endswith function to check whether the last "n" characters in the cube are equal to the string representation of the number you are passed. 您应该使用endswith函数检查多维数据集中的最后“ n”个字符是否等于所传递数字的字符串表示形式。

You could thus do: 因此,您可以这样做:

print(str(num_cube).endswith(num))

The way you have currently implemented it, you are "hard coding" the expected length of the number read from the stdin and are thus assuming it to always be of length 1. 您当前实现它的方式是对“从标准输入”读取的数字的预期长度进行“硬编码”,并因此假设其始终为长度1。

To correct your code, you would do the following: 要更正您的代码,请执行以下操作:

>>> num = "24"
>>> num_cube = str(pow(int(num), 3))
>>> num_cube[len(num_cube) - len(num):] == num
True
>>> num_cube[-len(num):] == num # negative indexing
True

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

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