如何通过索引从字符串中获取字符? [英] How to get char from string by index?
本文介绍了如何通过索引从字符串中获取字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个由 x 个未知字符组成的字符串.我怎么能得到 char nr.13 或字符编号.x-14?
解决方案
首先确保所需的数字是有效索引的字符串从头或尾,然后您可以简单地使用数组下标表示法.使用 len(s)
获取字符串长度
Lets say I have a string that consists of x unknown chars. How could I get char nr. 13 or char nr. x-14?
解决方案
First make sure the required number is a valid index for the string from beginning or end , then you can simply use array subscript notation.
use len(s)
to get string length
>>> s = "python"
>>> s[3]
'h'
>>> s[6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> s[0]
'p'
>>> s[-1]
'n'
>>> s[-6]
'p'
>>> s[-7]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>>
这篇关于如何通过索引从字符串中获取字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文