Check the first or last character of a string in python

In this article, we will discuss different ways to check the content of the first or last character of a string in python.

Indexing in String

Every character in a string has an index number associated with it. This index can be a positive or negative number. For example, we have a string,

sample_str = 'hello text'

In this, each character has a positive & negative index number associated with it,

The positive index starts from 0 to the size-1. Whereas the negative index for the last element is -1 and it keeps on decremented when we move from right to left. Let’s understand by an example,

For the string “hello text” indexes of characters are as follows,

  • ‘h’ has positive index 0 and negative index -10
  • ‘e’ has positive index 1 and negative index -9
  • ‘l’ has positive index 2 and negative index -8
  • ‘l’ has positive index 3 and negative index -7
  • ‘o’ has positive index 4 and negative index -6
  • ‘ ’ has positive index 5 and negative index -5
  • ‘t’ has positive index 6 and negative index -4
  • ‘e’ has positive index 7 and negative index -3
  • ‘x’ has positive index 8 and negative index -2
  • ‘t’ has positive index 9 and negative index -1

Let’s use this indexing to check conditions on first & last characters of a string.

Check the Last Character of a String in Python

Use negative indexing to check the last character of a string in python

To check the condition on the last character of the string, select the last element using negative index, i.e. -1,

# Check if last character is 't'
if sample_str[-1] == 't':
   print("Last character is 't' ")

Output:

Last character is 't'

Calculate size to check the last character of a string in python

To check the condition on the last character of a string,  get the size of the string first. Then check the content of character at index size -1,

size = len(sample_str)

# Check if last character is 't'
if sample_str[ size -1  ] == 't':
    print("Last character is 't' ")

Output:

Last character is 't'

Use endswith() to check the last character of a string in python

String class in python provides a function endswith() which accepts a character or tuple of characters and check if the string ends with the given character or not. Let’s use this to check if the last character of our string is ‘t’,

# Check if last character is 't'
if sample_str.endswith('t'):
   print("Last character is 't' ")

Output:

Last character is 't'

Check if the last character of a string matches with any of the given characters in python

endswith() provides an additional facility as compared to the previous solutions. In endswith(), we can pass a tuple of characters too, it will check if the last character of string matches with any of the character in the given tuple or not i.e.

# Characters to check
charsToMatch = ('d', 'p', 't')

# Check if string ends with any of the given character in tuple
if sample_str.endswith(charsToMatch):
   print("Ends with one of the given characters ")

Output:

Ends with one of the given characters

Check the first character of a string in python

Check the first character of a string using [] operator in python

A string is a sequence of characters and in it, indexing starts from 0. So, to check the first character of a string we need to select the character at 0th index i.e.

# Check if first character of the string is 'h'
if sample_str[0] == 'h':
   print("First character is 'h' ")

Output:

First character is 'h'

Use startswith() to check the first character of a string in python

String class in python provides a function startswith() which accepts a character or tuple of characters and check if a string starts with the given character or not. Let’s use this to check if the first  character of our string is ‘H’,

# Check if first character of the string is 'h'
if sample_str.startswith('h'):
   print("First character is 'h' ")

Output:

First character is 'h'

Check the first character of a string matches with any of the given characters

startswith () provides an additional facility. We can pass a tuple of character too, and it will check if the first character of string matches with any of the character in the given tuple or not i.e.

charsToMatch = ('d', 'h', 't')

# Check if string starts with any of the char in tuple
if sample_str.startswith(charsToMatch):
   print("Starts with one of the given characters ")

Output:

Starts with one of the given characters

The complete example is as follows,

def main():

    sample_str = 'hello text'

    print('*** Check Last Character of a String in Python ***')

    print('** Using Negative indexing **')

    # Check if last character is 't'
    if sample_str[-1] == 't':
       print("Last character is 't' ")

    print('** Using len() function  **')

    size = len(sample_str)

    # Check if last character is 't'
    if sample_str[ size -1  ] == 't':
        print("Last character is 't' ")

    print('** Use endswith() to check the last character of a string in python **')

    # Check if last character is 't'
    if sample_str.endswith('t'):
       print("Last character is 't' ")

    print('** Check if last character of a string matches with any of the given characters in python **')

    # Characters to check
    charsToMatch = ('d', 'p', 't')

    # Check if string ends with any of the given character in tuple
    if sample_str.endswith(charsToMatch):
       print("Ends with one of the given characters ")


    print('*** Check first character of a string ***')

    print('** Check first character of a string using [] operator **')

    # Check if first character of the string is 'h'
    if sample_str[0] == 'h':
       print("First character is 'h' ")

    print('** Check first character of a string using startswith() **')

    # Check if first character of the string is 'h'
    if sample_str.startswith('h'):
       print("First character is 'h' ")

    print('** Check first character of a string matches with any of the given characters **')

    charsToMatch = ('d', 'h', 't')

    # Check if string starts with any of the char in tuple
    if sample_str.startswith(charsToMatch):
       print("Starts with one of the given characters ")


if __name__ == '__main__':
   main()

Output:

*** Check Last Character of a String in Python ***
** Using Negative indexing **
Last character is 't' 
** Using len() function  **
Last character is 't' 
** Use endswith() to check the last character of a string in python **
Last character is 't' 
** Check if last character of a string matches with any of the given characters in python **
Ends with one of the given characters 
*** Check first character of a string ***
** Check first character of a string using [] operator **
First character is 'h' 
** Check first character of a string using startswith() **
First character is 'h' 
** Check first character of a string matches with any of the given characters **
Starts with one of the given characters 

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top