Home > Articles > Open Source > Python

How to Store Text in Strings in Python

  • Print
  • + Share This
  • 💬 Discuss
When Python wants to store text in a variable, it creates a variable called a string. Katie Cunningham shows you how to create, print and format strings and when to use strings in the real world.

When Python wants to store text in a variable, it creates a variable called a string. A string’s sole purpose is to hold text for the program. It can hold anything—from nothing at all (") to enough to fill up all the memory on your computer.

Creating Strings

Creating a string in Python is very similar to how we stored numbers in the last hour. One difference, however, is that we need to wrap the text we want to use as our string in quotes. Open your Python shell and type in the following:

>>> s = "Hello, world"
>>> s
'Hello, world'

The quotes can be either single (′) or double ("). Keep in mind, though, that if you start with a double quote, you need to end with a double quote (and the same goes for single quotes). Mixing them up only confuses Python, and your program will refuse to run. Look at the following code, where the text “Harold” starts with a double quote but ends with a single quote:

>>> name = "Harold'
File "<stdin>", line 1
name = "Harold'
^ SyntaxError: EOL while scanning string literal

As you can see, we got an error. We have to make the quote types match:

>>> name = "Harold"
>>> name
'Harold'
>>> name2 = 'Harold'
'Harold'
  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus