Python strings


a string, series of characters

A string is a series of characters, they are mostly used to display text.

To define a string simply type text between quotes. Python accepts single, double and triple quotes.

Related Courses:

String input and output

To output text (string) to the screen:

s = "hello world"

To get text from keyboard:

name = input("Enter name: ")

If you use an old Python version (2.x), you need to use:

name = raw_input("Enter name: ")

To test your version:
python –version

String Comparison

To test if two strings are equal use the equality operator (==).

sentence = "The cat is brown"
q = "cat"
if q == sentence:
    print('strings equal')

To test if two strings are not equal use the inequality operator (!=)

sentence = "The cat is brown"
q = "cat"
if q != sentence:
    print('strings equal')
String Slices (part 2)
This entry was posted in Beginner and tagged , , . Bookmark the permalink.

52 Responses to Python strings

  1. Ramu says:

    Why do I get syntax error, when I use the( ==) operator to compare equalities. For example if x = 3 and y = 3, when I press enter, I get a syntax error. Please tell me where I am going wrong.

    • Frank says:

      Are you running the code or using the interpreter directly?
      Do you see >>> before the text you type? If so, you have to create a file with the extension .py and execute with that as parameter.

  2. Geoffrey says:

    am much interested to learn programming,,am going through tutorials but is possible to get practical tutorials

  3. Jem says:

    You have spelled “concatenation” wrongly: the word is “concatenate” — note the ‘e’ in the middle — NOT “concatinate”. (It means ‘link together like a chain’ because it comes from the Latin ‘catena’ = chain.)

  4. Chan says:

    sir? can you explain the equality operations? i don’t get it……

    • Frank says:


      The equality operator (==) tests if two variables have an equal value. Given variable x=3 and y=3, we can test for equality using the statement if x == y, which will return true. If we change either x or y, it would return false. It looks like the assignment operator (=) , but the purpose of the assignment operator is only to set the variables data. You can use the operator on strings, integers, decimals and many other types of variables. To test for inequality use the not operator (!=).

  5. Shilpa says:

    sir, can u pls explain start index and past index clearly with exaples

  6. Saqib Ali Khan says:

    what does this comment lines implies that you add in every example: “#!/usr/bin/env python”??