[英]How to print the last two digits of a 4 digit input taken by the user?
# Read an integer:
a = input()
Over here I take an Input from the reader or the user who is using my app..... # Print a value: print(a[2, 3]) ...and then I want to print out only the last two digits but I am getting an error as follows: Traceback (most recent call last): File "python", line 4, in TypeError: string indices must be integers Example input what I wanted it to be : 1234 Example output what I wanted it to be : 34 Can you please explain me my error...在这里,我从阅读器或使用我的应用程序的用户那里获取输入..... # Print a value: print(a[2, 3]) ...然后我只想打印出最后两个数字,但我收到如下错误:回溯(最近一次调用最后一次):文件“python”,第 4 行,类型错误:字符串索引必须是整数 示例输入我想要的:1234 示例输出我想要的是:34 你能解释一下我的错误吗...
As the error message says: String indices must be integers.正如错误消息所说:字符串索引必须是整数。 You give it a tuple (of integers, but it's still a tuple).你给它一个元组(整数,但它仍然是一个元组)。 You should slice it with a[-2:]
.你应该用a[-2:]
切片。
Try this,尝试这个,
print(a[-2:])
This prints the last 2 characters of string a.这将打印字符串 a 的最后 2 个字符。
if you want the last two digits you can use print(a[-2:])
since python uses negative index to start form the last item.如果你想要最后两位数字,你可以使用print(a[-2:])
因为python使用负索引从最后一项开始。 also check if the length of the input is greater than 2 characters.还要检查输入的长度是否大于 2 个字符。
if len(a) >= 2:
print(a[-2:])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.