How to Concatenate Values in Python?

Estimated read time 2 min read

To concatenate values in Python, you can convert the values to strings and use string concatenation or string formatting techniques. Here are a few methods you can use:

  1. String Concatenation using the + operator:
# Concatenating values using the + operator
value1 = 10
value2 = 20
concatenated = str(value1) + str(value2)

print(concatenated)

In this example, the + operator is used to concatenate the values value1 and value2 after converting them to strings using the str() function.

  1. String Formatting using the % operator:
# Concatenating values using string formatting
value1 = 10
value2 = 20
concatenated = '%s%s' % (value1, value2)

print(concatenated)

In this method, the % operator is used for string formatting. The %s placeholder represents a string, and the values value1 and value2 are substituted into the string template.

  1. f-Strings (Python 3.6+):
# Concatenating values using f-strings
value1 = 10
value2 = 20
concatenated = f'{value1}{value2}'

print(concatenated)

In this method, an f-string is used, which is a string literal that is prefixed with the letter ‘f’. Inside the f-string, the values value1 and value2 are directly embedded within curly braces.

These methods can be applied to concatenate values of various types, including numbers, strings, or a combination of different types. Just ensure that you convert the values to strings using the str() function or appropriate string formatting techniques before concatenation.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply