简体   繁体   English

如何打印用户输入的 4 位数字的最后两位?

[英]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.

相关问题 允许用户输入3位数字,然后输出该数字中的各个数字 - to allow the user to input a 3-digit number, and then output the individual digits in the number 如何在Python中按最后一位数字降序打印数组? - How to print an array in Python by the last digit descendingly? 如何检查用户输入是否为数字 - How to check if user input is a digit 当两个文件的最后一位相同时打印行 - Print lines when Last digit of two files are same 尝试打印从 0 到 x 的范围,用一个单词替换偶数位,并为我的最后一位数字获取 None - Trying to print a range from 0 to x, replacing even digits with a word, and getting None for my last digit 我怎样才能得到与个位数一致的两位数的数字坐标列的最后一位 - How can i get the number coordinate column last digit of the double digits in line with the single digits 从用户获取所有输入后如何打印值? (不存储输入值) - How do I print values after all the input has been taken from user? (without storing the input values) 如何在Python中用点号分隔最后两位数字 - How to seperate last two digits with dot in Python 当且仅当一个数字至少有两个连续的数字都等于 3,或者它的最后一位数字可以被 4 整除时,它才不是苍白的 - A number is not pale if and only if it has at least two consecutive digits each equal to 3, or if its last digit is divisible by 4 按顺序打印3位数字的数字 - Print the digits of a 3-digit number in order
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM