HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

11) User Input and String Formatting Lesson

Python String Mini Language

9 min to complete · By Martin Breuss

In this lesson, you'll get to know a few more helpful tricks to work with strings in Python:

  1. String formatting mini-language
  2. Character escaping
  3. String concatenation using parentheses

These tips will help you work with longer strings effectively, and you can apply what you need when building out your command-line game.

String Formatting Mini-Language

Python strings include their own mini-language that you can use only inside of the curly braces ({}) of your f-strings as well as in str.format().

Run the code below in your interpreter and play around with it:

message = "you move me!"
print(f"{message:>20}")

If you run this code, then you'll see that Python moves the message in your string off from the left side of the terminal.

The mini-language inside of the curly braces allows you to format the injected values.

String Mini-Language Practice

  • Play around with this example. You can read more about how to use it in the string mini-language documentation.
  • Why did Python add exactly the amount of spaces on the left side that it did?
  • What happens when you change the number from 20 to another value?
  • What happens when you use a different operator instead of >? Can you figure out their meaning?

The string mini-language is quite powerful and gives you a quick way to add additional formatting to your string values. It works both for f-strings and strings on which you call the .format() method.

Character Escaping

Sometimes, you'll need to include a character with a specific meaning in your string. The most common situation that you'll encounter is when you want to have the quote character that you're using to start a string also as a part of the string:

message = "The door reads "Do Not Enter!""  # SyntaxError

This code will produce a SyntaxError because Python assumes you ended the string with the second double-quotation mark. As you've already learned, you can circumvent this problem by using the other type of quotation marks:

message = "The door reads 'Do Not Enter!'"
message = 'The door reads "Do Not Enter!"'

Either type of quotation marks, single (') or double ("), work, but you can only use the other type inside your string.

There is an alternative to swapping out the quotes, which is character escaping:

message = "The door reads \"Do Not Enter!\""

Strip Functionality with Backslash

In Python, you can use the backslash character (\) in front of a character that has a specific functional meaning. This will strip it of its usual functionality and treat it as a normal character.

One of the characters you can escape that helps you format long strings is the newline character (\n), which constitutes a line break. This character is always there as an indicator to start a new line, even though you can't see it represented in the same way as most other characters:

print("""hi there,
friend""")

Following the comma (,) in the code snippet above, there is a newline character (\n) that you see not in its character form, but by the fact that the next word friend appears in a new line.

If you wanted to print the whole message in one line, you'd need to escape the newline character. You can do this using the backslash character:

print("""hi there,\
friend""")

This might come in handy when you need to write a long message that you want to appear in one line, but to make the message easier to maintain in your code, you want to display it over multiple lines:

long_str = "check out this very long string that is \
full of wisdom so you should definitely keep \
reading all the way to the end!"

print(long_str)  # Prints in one line

Errors with Backslash

However, you need to be careful with your formatting if you use this technique. The backslash character just escapes the newline character, which means that everything that follows afterward will be considered part of your string.

If you format your string like shown in the example below, you probably won't get the result you were looking for:

long_str = "check out this very long string that is full \
            of wisdom so you should definitely keep reading \
            all the way to the end!"

print(long_str)

Because the backslash escapes the newline character and continues the string, the indentation you added for the second line will become part of your string. Is there a way around this? There is!

String Concatenation with Parentheses

If you wrap multiple strings broken up into multiple lines inside of parentheses, then you can concatenate them into one long string:

long_str = ("hei there "
            "how are you?"
            " remember that this ends up as one string!")

print(long_str)

The advantage of using the parentheses instead of escaping the newline character is that it allows you to indent the code. Python concatenates the different string pieces to create one string. When escaping the newline character, as in the example further up, Python continues the string into the next line.

Using parentheses around multiple pieces of a string in multiple lines also works with f-strings. Give it a try and run the code in your text editor.

These tricks can help format your messages both as output to your users and keep longer text that is easier to read within your code. Apply whichever of these techniques you need when building your command-line game.

Summary: Python String Mini-Language

  • The string formatting mini-language allows you to use {} to format strings
  • Character escaping is done using the backslash \ to strip functionality from special characters
  • Accidentally using a backslash can cause errors in your program
  • Parentheses can be used to automatically concatenate strings on multiple lines