Python: Get the first character of the first string in a list?

后端 未结 4 735
不知归路
不知归路 2020-12-23 10:38

How would I get the first character from the first string in a list in Python?

It seems that I could use mylist[0][1:] but that does not give me the f

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-23 11:26

    Get the first character of a bare python string:

    >>> mystring = "hello"
    >>> print(mystring[0])
    h
    >>> print(mystring[:1])
    h
    >>> print(mystring[3])
    l
    >>> print(mystring[-1])
    o
    >>> print(mystring[2:3])
    l
    >>> print(mystring[2:4])
    ll
    

    Get the first character from a string in the first position of a python list:

    >>> myarray = []
    >>> myarray.append("blah")
    >>> myarray[0][:1]
    'b'
    >>> myarray[0][-1]
    'h'
    >>> myarray[0][1:3]
    'la'
    

    Many people get tripped up here because they are mixing up operators of Python list objects and operators of Numpy ndarray objects:

    Numpy operations are very different than python list operations.

    Wrap your head around the two conflicting worlds of Python's "list slicing, indexing, subsetting" and then Numpy's "masking, slicing, subsetting, indexing, then numpy's enhanced fancy indexing".

    These two videos cleared things up for me:

    "Losing your Loops, Fast Numerical Computing with NumPy" by PyCon 2015: https://youtu.be/EEUXKG97YRw?t=22m22s

    "NumPy Beginner | SciPy 2016 Tutorial" by Alexandre Chabot LeClerc: https://youtu.be/gtejJ3RCddE?t=1h24m54s

提交回复
热议问题