Skip to content

How To Get First Characters of a String in Python

  • by
Get First Characters of a String in Python

Way to find the first characters of a string using Python. Here we go.

String provides an [] operator to accept any character in it by index position in Python. To get the first character you have to pass the index position in the large bracket. You will get a return while passing the value.

Let’s get started.

Get the first characters of a string in Python

As you know, in Python, the string character index starts from 0. Now you want to get the first character of a string just use the [] operator i.e, and call the print (0).

Let’s follow the below code.

# Get first character of string i.e. char at index position 0

#                      0123456789
get_first_character = "WHOlEBLOGs"
first_char = get_first_character[0]
print('First character : ', get_first_character[0])

We want to show you some ways that can save your time and that are very easy to use.

Let’s see what is that.

Here we made three variables with the following name:

  • start_index_pos:
  • end_index_pos:
  • step_size:

start_index_pos: it fetches values from the beginning, and as you know well in Python there is a default value in starting like 0.

Why not have an example as well?

start_index_pos = "WHOlEBLOGS"

first_char = start_index_pos[0]
print(first_char)

end_index_pos: Wanna get the last value of the string? With the help of this simple variable. I hope it will be helpful to you. It saves all kinds of position in it. The default value is the end of the string.

end_index_pos = "WHOlEBLOGS"

first_char = end_index_pos[-1]
print(first_char)

step_size: Here you can get the interval value. Its default is 1.

 

step_size = "WHOLEBLOGS"

interval_char = step_size[5:10]
print(interval_char)

SyntaxError: String index out of range

Why are you getting string index out of range again and again? Before calling the variable you made just assign the len() function over there. It will return the exact value according to what you want. Python has a range() function for the help of picking the exact string you want.

Here I have completed a simple guide for you. I hope you liked it.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *