Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 first character.

>>> mylist = [] >>> mylist.append("asdf") >>> mylist.append("jkl;") >>> mylist[0][1:] 'sdf' 
like image 989
Trcx Avatar asked Aug 18 '11 13:08

Trcx


People also ask

How do you check the first character of a string in a list Python?

String Indexing Individual characters in a string can be accessed by specifying the string name followed by a number in square brackets ( [] ). String indexing in Python is zero-based: the first character in the string has index 0 , the next has index 1 , and so on.

How do you get the first character of a string?

To get the first and last characters of a string, use the charAt() method, e.g. str. charAt(0) returns the first character, whereas str. charAt(str. length - 1) returns the last character of the string.

How do you print the first letter of each item in a list in Python?

You need to change it to be print(fish[i][0:1]) so you take the first character instead of trying to do something to the int i . The slice is also unnecessary. If you only want the first element print(fish[i][0]) is enough. Save this answer.


1 Answers

You almost had it right. The simplest way is

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 

would also work.

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

like image 155
agf Avatar answered Oct 06 '22 07:10

agf