python logo


Tag: compare

python if string equals

A string in Python represents a sequence of characters and is a fundamental data type in the language. Strings are predominantly utilized for displaying and manipulating text.

Strings can be defined by enclosing text within quotes. Python supports various types of quotes, including single ('), double ("), and triple (''' or """).

Related Course:
Python Programming Bootcamp: Go from zero to hero

Displaying and Receiving String Input


To display a string on the screen, you can use the print function. For instance:

s = "hello world"
print(s)

If you need to retrieve a string input from the user via the keyboard, the input function comes in handy:

name = input("Enter name: ")
print(name)

Note: If you are utilizing an older version of Python (2.x), the raw_input function is used instead of input:

name = raw_input("Enter name: ")
print(name)

To ascertain your Python version, you can execute the command:
python –version

Comparing Strings in Python


In Python, the equality operator (==) lets you check if two strings are identical. For example:

sentence = "The cat is brown"
q = "cat"

if q == sentence:
print('strings are identical')

Conversely, to see if two strings are different, employ the inequality operator (!=):

sentence = "The cat is brown"
q = "cat"

if q != sentence:
print('strings are not identical')

Enhance your Python skills further with exercises:
Download Python Exercises

For more tutorials, navigate: