How To Get First Characters of a String in Python

Share This Post

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]

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]

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


step_size = "WHOLEBLOGS"

interval_char = step_size[5:10]

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.


Related Posts

5 Reasons That Make MacBooks Good for Coding

Looking for a reliable laptop or computer for coding?...

Python for Loop Iteration: How to Easily Manipulate a List

One of the most powerful features of the Python...

How To Convert Tuple To String In Python

In this post, you will learn how to convert...

How To Convert String to Double in Python

Good to hear, that you want to convert a...

Python TypeError: String Index Out Of Range Solution

A string is an array of characters and part...

How To Remove Empty Strings From a List Of Strings

On this page, we will discuss how to remove...
- Advertisement -spot_img