Add Spaces

Add Spaces in Python – (Add Leading, Trailing Spaces to string)

Add spaces in python with example : In this Tutorial we will learn how to add Spaces (leading, Trailing Spaces to string) in python for following Scenarios.

  • Add Space at the start of the string in Python – rjust() function in python

  • Add space at the end of the string in Python – ljust() function in python

  • Add white spaces at start and end of the string in python – center() function in python.

  • Add space between every letter of the string in python.

Add Spaces in python at the start of the string:

## Add the space at Start of the string in Python
 
string2="Test String leading space to be added"
string_length=len(string2)+10    # will be adding 10 extra spaces
string_revised=string2.rjust(string_length)
print (string_revised)


# ‘          Test String leading space to be added’

In the above example we will be adding 10 extra spaces at start of the string, with the help of rjust() function.

So the output will be‘ Test String leading space to be added’

Add spaces in python at the end of the string

## Add the space at end of the string in Python
 
string1="Test String Trailing space to be added"
string_length=len(string1)+10    # will be adding 10 extra spaces
string_revised=string1.ljust(string_length)
print (string_revised)

# ‘Test String Trailing space to be added          ‘ 

In the above example we will be adding 10 extra spaces at end of the string, with the help of ljust() function

So the output will be‘Test String Trailing space to be added ‘

Add white spaces at start and end of the string:

## Add the space at Start and end of the string in Python
 
string3="Test String leading and trailing space to be added"
string_length=len(string3)+10    # will be adding 10 extra spaces
string_revised=string3.center(string_length)
print (string_revised)

# Test String leading and trailing space to be added   

In the above example we will be adding 10 extra spaces, 5 at the start and 5 at end of the string, with the help of center() function.

So the output will be‘ Test String leading and trailing space to be added ‘

Add spaces in python between every letter of the string:

In the above example we will be adding a space between each letter of the string. So the output will be ‘T e s t S t r i n g’

## Add the space between every letter of the string
 
string4="Test String"
string_revised=" ".join(string4)
print (string_revised)

# ‘T e s t   S t r i n g’          

In the above example we will be adding a space between each letter of the string.

So the output will be‘T e s t S t r i n g’

PYTHON STRINGS TUTORIAL

Last updated