How To Add A Certain Number Of Spaces To A String In Python

Continuing the series of lessons for developers, I will show you how to add a certain number of spaces to a string in Python. Please read the article below to do it.

Two ways to add a certain number of spaces to a string in Python

Use (+) operator

Of course, that’s the simplest and most basic way.

In other programming languages, the (+) operator is commonly used with numeric data types. However, in newer programming languages, it can be used to concatenate strings, including Python.

For this requirement, I can concatenate the original string with a string of spaces characters anywhere in the string because space characters are still a string when initialized in ‘ ‘.

Example

strs = 'I am a student'
spaces = '      '
strWithSpace = strs + spaces

# Log the result
print(strWithSpace)
print(len(strs))
print(len(spaces))
print(len(strWithSpace))

For the example above, I declare an original string and add it to a space string using the (+) operator to get the desired result.

I will check the result by logging the original string length, spaces string length, new string length, and the value of the new string.

Output

'I am a student      '
14
6
20

For more difficult wishes than adding spaces between, we can split the original string in two and add the following spaces.

str1 = 'I am a student'
str2 = 'and I come from LearnShareIT'
spaces = '      '
strWithSpace = str1 + spaces + str2

# Log the result
print(strWithSpace)
print(len(str1), len(str2))
print(len(spaces))
print(len(strWithSpace))

As well as printing the prices as above, we have the following results.

I am a student      and I come from LearnShareIT
14 28
6
48

Combine (+) and (*) operator

Python supports many Arithmetic Operators, operator (*) being one of them.

Operator (*) means multiplication, they can be used to multiply the number of data types or help multiply a string type. To add a certain number of spaces to a string in Python, I can use the (*) operator to do the following.

strs = 'I am a member of LearnShareIT'
strWithSpace = strs + ' ' * 6

# Log the result
print(strWithSpace)
print(len(strs))
print(len(strWithSpace))

Firstly, initialize the string and add spaces. Then use the (*) operator to multiply the number of spaces and add them to the original string. I finally printed out the resulting string after adding the original string length and the new string length for comparison. Python supports flexible operators (+) and (*) in strings, which is the strength of this programming language.

Output

'I am a member of LearnShareIT      '
29
35

Summary

To add a certain number of spaces to a string in Python, we can use the operators available in it. The potential to apply them to mathematical problems is huge. In the above article, I have implemented them most simply. Thank you for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *