Python strings


python-string
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.

Video: Strings Get PDF
Get Exercises Quiz

String input and output

To output text (string) to the screen:

s = "hello world"
print(s)

To get text from keyboard:

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

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

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

To test your version:
python –version

String Comparison

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

#!/usr/bin/python
 
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 (!=)

#!/usr/bin/python
 
sentence = "The cat is brown"
q = "cat"
 
if q != sentence:
    print('strings equal')

52 thoughts on “Python strings

  1. Ramu - December 10, 2015

    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.

    1. Frank - December 10, 2015

      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 - September 21, 2015

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