python

Python code to get the first character from a string

The below code can be used to get the very first character from a string.

my_str = "Cool Stuffs"

#First example
first_char_1 = my_str[0]
print(first_char_1) # -> C

#Second example
first_char_2 = my_str[:1]
print(first_char_2) # -> C

We have introduced two methods in the above code snippet to get the very first character of a string. We are using the character index of the string to get the characters. To get the first character we are using string[0].

str_line = "Data is the new fuel"

print(str_line[0]) # -> D
print(str_line[:1]) # -> D
print(str_line[0:1]) # -> D
All the above lines of code will return the very first character of the string.
fruits = ["Banana", "Apple", "Orange", "Papaya"]

first_char = fruits[0][0]
print(first_char) # -> B
If you have a list and you want to get the first character from a list item then you can follow the below steps.

1. First, get the list item using its index.
2. Use 0 index to get the first character from this item as shown in the above code.
Was this helpful?