How to insert variables into a String in Python

How to insert variables into a String in Python. That’s the topic I want to introduce to you today. There are many ways to insert a variable into a string. This article will show you three ways: using commas, format() function, and f-string. If you’re curious about this topic, read it all. 

Inserting variables into a String in Python

Use commas

Using commas is an easy and common practice, but one downside is the inability to customize large volumes of data.

Example:

name = 'John'
age = 16
habits = 'Football'

# Use commas to insert the variable into the string.
print('Name:', name, '; Age:', age, '; Habits:', habits)

Output:

Name: John ; Age: 16 ; Habits: Football

Use the 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:

  • Use the format() function to format two strings through pattern: {:3s}, which has the effect of formatting the string.
firstStr = 'Hello'
secondStr = 'This is a lesson in Python tutorials.'

# Use the format() method to insert variables into a string.
print('{:3s}! {:3s}'.format(firstStr, secondStr))

Output:

Hello! This is a lesson in Python tutorials.

Use f-string

Syntax:

f'a{value:pattern}b'

Parameters:

  • f character: use the string f to format the string.
  • a,b: characters to format.
  • {value:pattern}: string elements need to be formatted.
  • pattern: string format.

Example:

firstStr = 'Hello'
secondStr = 'This is a lesson in Python tutorials.'

# Use the f-string to insert variables into a string.
print(f'{firstStr}! {secondStr}')

Output:

Hello! This is a lesson in Python tutorials.

Use % formatting

This type of formatting is familiar once you’ve been exposed to the C language.

Syntax:

<string>% (1st value, 2nd value, ….)

Example:

firstStr = 'Hello'

# Use % formatting
newStr = ('%s! This is a lesson in Python tutorials.' % (firstStr))
print('New string:', newStr)

Output:

New string: Hello! This is a lesson in Python tutorials.

Summary

The article insert variables into a String in Python would like to stop here. I hope you found a method that works for you if you don’t have any ideas. Use the format() function, which is relatively easy to understand and implement. Or an f-string is also a good choice, depending on your case, which way is reasonable to use. If you have any suggestions or comments about the article, please comment.

Leave a Reply

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