How To Add Space Between Variables In Python

How to add space between variables in Python

To add space between variables in Python, we can use the add operator, format() function, join() function. Follow the article to understand better.

How to add space between variables in Python

Use the addition operator

Example:

  • The addition operator to concatenate two variables combines the use of spaces to get a space between two variables.
  • You can create as many spaces as you want. I just left a space between the two variables in the example below.
var1 = 12 
var2 = 14

# Use the add operator
resultStr = str(var1) + ' ' + str(var2)
print('Concatenate two variables and add a space in between:', resultStr)

Output:

Concatenate two variables and add a space in between: 12 14

Use format() function

Syntax:

format(value[, format_spec])

Parameters:

  • value: value to be formatted.
  • format_spec: format you want to use for ‘value’.

The format() method returns the formatted result of a given value specified by the specified formatting.

Example:

  • Initialize two variables whose value is the string.
  • Use the format() function to concatenate two variables and add a space between them.
  • ‘{0} {1}’ pairs are called surrogate fields in that string format.
firstStr = 'We are' 
secondStr = 'learnshareit'

# Use the format() function
resultStr = '{0} {1}'.format(firstStr, secondStr)
print(resultStr)

Output:

We are learnshareit

Use the join() function

The join() function is also a good option where you can add a space between two variables.

Syntax:

str.join(object)

Parameters:

  • str: Delimiter for string concatenation.
  • object: List or tuple containing elements that are strings to be concatenated.

The join() function returns an object that is a character string of the elements of the specified list or tuple joined together by a delimiter.

Example:

  • Initialize two variables whose value is the string.
  • Use the join() function to add a space between two variables.
firstStr = 'We are' 
secondStr = 'learnshareit'

# Use the join() function
resultStr = ' '.join([firstStr, secondStr])

print('Concatenate two variables and add a space in between:', resultStr)

Output:

Concatenate two variables and add a space in between: We are learnshareit

Summary

Above is everything I want to show you about how to add space between variables in Python. Hopefully, after reading, you will have an idea for your work. If you have any questions about this article, leave a comment below. I will answer your questions. Thank you for reading!

Maybe you are interested:

Leave a Reply

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