Python: get the first character of the first line in a list?

How do I get the first character from the first line of a list in Python?

It seems that I could use mylist[0][1:] , but that does not give me the first character.

 >>> mylist = [] >>> mylist.append("asdf") >>> mylist.append("jkl;") >>> mylist[0][1:] 'sdf' 
+48
python string list character
Aug 18 '11 at 13:21
source share
4 answers

You had almost everything right. The easiest way -

 mylist[0][0] # get the first character from the first item in the list 

but

 mylist[0][:1] # get up to the first character in the first item in the list 

will also work.

You want to end after the first character (zero character), and not start after the first character (zero character), which is what the code in your question means.

+76
Aug 18 '11 at 13:25
source share

Indexing in python starting at 0. You wrote [1:], this will not return the first char to you anyway - it will return the rest (except the first char) of the string to you.

If you have the following structure:

 mylist = ['base', 'sample', 'test'] 

And I want to get a char fist for the first line (item):

 myList[0][0] >>> b 

If all the first characters are:

 [x[0] for x in myList] >>> ['b', 's', 't'] 

If you have text:

 text = 'base sample test' text.split()[0][0] >>> b 
+9
Aug 18 2018-11-18T00:
source share

Get the first character of an empty 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 here because they mix Python list object operators and Numpy ndarray object operators:

Numpy operations are very different from python list operations.

Wrap your head around two conflicting worlds of Python, “list slicing, indexing, subset,” and then “Masking, slicing, subset, indexing,” “Numping,” and then numpy Enhanced fancy indexing.

These two videos cleaned me up:

"Losing your cycles, fast numerical calculations with NumPy" from PyCon 2015: https://youtu.be/EEUXKG97YRw?t=22m22s

"Beginner for Beginners" SciPy 2016 Tutorial "by Alexander Chabot LeClerc: https://youtu.be/gtejJ3RCddE?t=1h24m54s

+7
Oct 02 '15 at 18:37
source share

Try mylist[0][0] . This should return the first character.

+3
Aug 18 '11 at 13:23
source share



All Articles