简体   繁体   中英

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?

You can get the first element of any sequence with [0] . Since a string is a sequence of characters, you're looking for s[0] :

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

For a detailed explanation, refer to the Python tutorial on strings .

负索引从右侧开始计数。

digit = mystring[-1]

In Python, a sting is something called, 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] .

  • If you need to get the last (character) in a string (the final 1 in the string you provided), then use 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 ).

  • If you have a float, on the other hand, you are best of str(my_float)[-1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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