Python Strings - Compare first N characters


Python Strings - Compare first N characters

You can compare the first n characters of two Python strings by slicing the strings and then using the Equal-to comparison operator == to compare the sliced portions.

In this tutorial, we will see how to compare the first n characters in given two strings, with a step by step process, and examples.

Steps to compare first N characters in the strings in Python

  1. Given two strings in x and y.
  2. Given an integer value in n. This is the number of first characters in the string to compare.
  3. Slice the string x to get the first n characters, using the expression x[:n]. You may refer Get first n characters in Python string tutorial.
  4. Slice the string y to get the first n characters, using the expression y[:n].
  5. Compare the two slices using Equal-to comparison operator ==. The expression is x[:n] == y[:n]. This expression returns True if the first n characters from the two strings x and y are equal, or False otherwise. You can use this expression as a condition in a Python if else statement.

Program

The complete program to compare the first n characters in given two strings is given below.

In this program, we shall compare the first five characters from the given two strings, i.e., n=5.

Python Program

# Given strings
x = "Hello World!"
y = "Hello User!"

# n value
n = 5

# Compare the first n characters
if x[:n] == y[:n]:
    print(f'The first {n} characters are equal.')
else:
    print(f'The first {n} characters are not equal.')

Output

The first 5 characters are equal.

Since the first 5 characters from the given two strings are "Hello" and "Hello", which are equal, the equal-to comparison operator returns True, and the if-block executes.

Let us change the value of n to 7, and observe the output.

Python Program

# Given strings
x = "Hello World!"
y = "Hello User!"

# n value
n = 7

# Compare the first n characters
if x[:n] == y[:n]:
    print(f'The first {n} characters are equal.')
else:
    print(f'The first {n} characters are not equal.')

Output

The first 7 characters are not equal.

Summary

In this tutorial of Python string tutorials, we learned how to compare the first n characters in given two strings using string slicing and equal-to comparison operator, with step by step process and example programs.