How to get char from string by index?

后端 未结 7 1037
青春惊慌失措
青春惊慌失措 2020-11-29 04:25

Lets say I have a string that consists of x unknown chars. How could I get char nr. 13 or char nr. x-14?

7条回答
  •  Happy的楠姐
    2020-11-29 04:43

    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 "", line 1, in 
    IndexError: string index out of range
    >>> s[0]
    'p'
    >>> s[-1]
    'n'
    >>> s[-6]
    'p'
    >>> s[-7]
    Traceback (most recent call last):
      File "", line 1, in 
    IndexError: string index out of range
    >>> 
    

提交回复
热议问题