6Strings
Whenever you speak, you use a combination of words to form sentences. If you want to use words and sentences in Python, you'll have to create a string. You can use strings as a variable value or use strings to print words or phrases. You can also manipulate strings using Python!
Create a String
A string is a set of characters used for creating words or sentences in Python. A string can be surrounded by either single quotes or double quotes.
You can view how a string looks once your Python program runs by using print
()
.
>>> name = 'Monty'
>>> print(name)
Monty
If you're typing a long string, it's sometimes best to type the string across multiple lines (also known as line breaks) so that the string is easier to read in the program. In IDLE, you can use a triple quote ("""
) before and after the string to create a string on multiple lines. Press Ctrl+J (Windows) or Control + J (Mac) in IDLE to begin typing on a new line.
>>> story = """Once upon a time in
a galaxy far far away was a coder
who loved nothing more than to code in Python!"""
>>> print(story)
Once upon a time in
a galaxy far far away was a coder
who loved nothing more than to code in Python!
Escape Characters
If you write a string that includes apostrophes, consider surrounding the string with double quotes. Likewise, if you write a string that includes quotations, consider surrounding the string with ...
Get Bite-Size Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.