简体   繁体   English

Python:如何通过其索引引用字符串中的数字?

[英]Python: How to refer to a digit in a string by its index?

I feel like this is a simple question, but it keeps escaping me... 我觉得这是一个简单的问题,但它一直在逃避我。

If I had a string, say, "1010101", how would I refer to the first digit in the string by its index? 如果我有一个字符串,例如“ 1010101”,我如何通过其索引引用字符串的第一个数字?

You can get the first element of any sequence with [0] . 您可以使用[0]获得任何序列的第一个元素。 Since a string is a sequence of characters, you're looking for s[0] : 由于字符串是字符序列,因此您正在寻找s[0]

>>> s = "1010101"
>>> s[0]
'1'

For a detailed explanation, refer to the Python tutorial on strings . 有关详细说明,请参阅有关stringPython教程

负索引从右侧开始计数。

digit = mystring[-1]

In Python, a sting is something called, subscriptable . 在Python中,字符串被称为subscriptable That means that you can access the different parts using square brackets, just like you can with a list. 这意味着您可以使用方括号访问不同的部分,就像使用列表一样。

  • If you want to get the first character of the string, then you can simply use my_string[0] . 如果要获取字符串的第一个字符,则只需使用my_string[0]

  • If you need to get the last (character) in a string (the final 1 in the string you provided), then use my_string[-1] . 如果需要获取字符串中的最后一个(字符)(您提供的字符串中的最后一个1 ),请使用my_string[-1]

  • If you originally have an int (or a long ) and you are looking for the last digit, you are best off using % (modulous) ( 10101 % 10 => 1 ). 如果您最初有一个int (或long ),并且正在寻找最后一位数字,则最好使用% (模数)( 10101 % 10 => 1 )。

  • If you have a float, on the other hand, you are best of str(my_float)[-1] 另一方面,如果有浮点数,则最好使用str(my_float)[-1]

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

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