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'
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With