How to Add Leading Spaces in Python

Save

Python's built-in string class comes with a powerful set of tools for manipulating and formating strings. There is more than one way to format a string to use leading spaces, depending upon how you want Python to perform the operation and what output you desire. The first is simply to create a new string, assigned to the same variable name. The other is to use the "rjust" command.

  • Open the Python interpreter or an existing Python program file.

  • Define a string by typing the following into your text editor or Python interpreter:

    s = 'This is a string.'

  • Type the following to insert a few blank spaces into the front of the string:

    s = ' ' + s

  • Type the following if, instead, you want to right-justify the string by filling all the leading characters with spaces. This will create a new string with a width of "100" and put the text already in the string at the right side of the string, filling the blank areas with spaces. Type this:

    s = s.rjust(100)

Tips & Warnings

  • Strings in Python are immutable; they cannot be changed after they are defined. So, in order to add characters to the string, you must create a new string of the same name. This an essential aspect of Steps 3 and 4.

References

Promoted By Zergnet

Comments

You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!