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.
How to Create a Chart in Python
Displaying data in the form of charts or graphs in Python requires the use of specialized, external code libraries, and the open-source...
How to Extract a Zip File With Python
Python is an open license programming language available in Windows, Linux and Mac, plus Java .Net virtual machines. Python features three versions,...
How to Remove Leading Blank Spaces in Excel
Sometimes during data entry, unnecessary spaces are introduced in front of the useful data. This can happen when a name is entered...
How to Remove Whitespace From a String in Excel
Microsoft Excel comes with an arsenal of tools that can help you efficiently perform data clean-up tasks. For instance, to remove whitespace...
How to Replace Regex on Python
The Python programming language uses regular expressions for pattern matching. Programmers often use regular expressions to search text for patterns of letters,...