Concatenating string in python

7 Ways to Concatenate Strings in Python

Summary: in this tutorial, you’ll learn various ways to concatenate strings in Python.

Python provides you with various ways to concatenate one or more strings into a new string.

Since Python string is immutable, the concatenation always results in a new string.

1) Concatenating literal strings

To concatenate two or more literal strings, you just need to place them next to each other. For example:

s = 'String' ' Concatenation' print(s)Code language: PHP (php)
String ConcatenationCode language: JavaScript (javascript)

Note that this way won’t work for the string variables.

2) Concatenating strings using the + operator

A straightforward way to concatenate multiple strings into one is to use the + operator:

s = 'String' + ' Concatenation' print(s)Code language: PHP (php)

And the + operator works for both literal strings and string variables. For example:

s1 = 'String' s2 = s1 + ' Concatenation' print(s2)Code language: PHP (php)
String ConcatenationCode language: JavaScript (javascript)

3) Concatenating strings using the += operator

Similar to the + operator, you can use the += operator to concatenate multiple strings into one:

s = 'String' s += ' Concatenation' print(s)Code language: PHP (php)
String ConcatenationCode language: JavaScript (javascript)

4) Concatenating strings using the join() method

The join() method allows you to concatenate a list of strings into a single string:

s1 = 'String' s2 = 'Concatenation' s3 = ''.join([s1, s2]) print(s3)Code language: PHP (php)

The join() method also allows you to specify a delimiter when concatenating strings. For example:

s1 = 'String' s2 = 'Concatenation' s3 = ' '.join([s1, s2]) print(s3)Code language: PHP (php)
String ConcatenationCode language: JavaScript (javascript)

In this example, we use the join() method to concatenate strings delimited by a space.

The following example use the join() method to concatenate strings delimited by a comma:

s1, s2, s3 = 'Python', 'String', 'Concatenation' s = ','.join([s1, s2, s3]) print(s)Code language: PHP (php)
Python,String,ConcatenationCode language: JavaScript (javascript)

5) Concatenating strings using the %-formatting

String objects have the built-in % operator that allows you to format strings. Also, you can use it to concatenate strings. For example:

s1, s2, s3 = 'Python', 'String', 'Concatenation' s = '%s %s %s' % (s1, s2, s3) print(s)Code language: PHP (php)
Python String ConcatenationCode language: JavaScript (javascript)

In this example, Python substitutes a %s in the literal string by corresponding string variable in the tuple that follows the % operator.

6) Concatenating strings using the format() method

You can use the format() method to concatenate multiple strings into a string. For example:

s1, s2, s3 = 'Python', 'String', 'Concatenation' s = '<> <> <>'.format(s1, s2, s3) print(s)Code language: PHP (php)
Python String ConcatenationCode language: JavaScript (javascript)

In this example, you use the <> in the string literal and pass the string that you want to concatenate to the format() method. The format() method substitutes the <> by the corresponding string argument.

7) Concatenating strings using f-strings

Python 3.6 introduced the f-strings that allow you to format strings in a more concise and elegant way.

And you can use the f-strings to concatenate multiple strings into one. For example:

s1, s2, s3 = 'Python', 'String', 'Concatenation' s = f'  ' print(s)Code language: PHP (php)
Python String ConcatenationCode language: JavaScript (javascript)

Which method should you use to concatenate strings

Even though there’re multiple ways to concatenate strings in Python, it’s recommended to use the join() method, the + operator, and f-strings to concatenate strings.

Источник

Python String Concatenation

Python String Concatenation

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

String Concatenation is a very common operation in programming. Python String Concatenation can be done using various ways. This tutorial is aimed to explore different ways to concatenate strings in a python program.

Python String Concatenation

  • Using + operator
  • Using join() method
  • Using % operator
  • Using format() function
  • Using f-string (Literal String Interpolation)

String Concatenation using + Operator

This is the most simple way of string concatenation. Let’s look at a simple example.

s1 = 'Apple' s2 = 'Pie' s3 = 'Sauce' s4 = s1 + s2 + s3 print(s4) 

Output: ApplePieSauce Let’s look at another example where we will get two strings from user input and concatenate them.

s1 = input('Please enter the first string:\n') s2 = input('Please enter the second string:\n') print('Concatenated String =', s1 + s2) 
Please enter the first string: Hello Please enter the second string: World Concatenated String = HelloWorld 

python string concatenation

It’s very easy to use + operator for string concatenation. However, the arguments must be a string.

>>>'Hello' + 4 Traceback (most recent call last): File "", line 1, in TypeError: can only concatenate str (not "int") to str 

We can use str() function to get the string representation of an object. Let’s see how to concatenate a string to integer or another object.

print('Hello' + str(4)) class Data: def __init__(self, i): self.id = i def __str__(self): return 'Data[' + str(self.id) + ']' print('Hello ' + str(Data(10))) 

The biggest issue with + operator is that we can’t add any separator or delimiter between strings. For example, if we have to concatenate “Hello” and “World” with a whitespace separator, we will have to write it as «Hello» + » » + «World» .

String concatenation using join() function

We can use join() function to concatenate string with a separator. It’s useful when we have a sequence of strings, for example list or tuple of strings. If you don’t want a separator, then use join() function with an empty string.

s1 = 'Hello' s2 = 'World' print('Concatenated String using join() =', "".join([s1, s2])) print('Concatenated String using join() and whitespaces =', " ".join([s1, s2])) 
Concatenated String using join() = HelloWorld Concatenated String using join() and spaces = Hello World 

String Concatenation using % Operator

We can use % operator for string formatting, it can be used for string concatenation too. It’s useful when we want to concatenate strings and perform simple formatting.

s1 = 'Hello' s2 = 'World' s3 = "%s %s" % (s1, s2) print('String Concatenation using % Operator =', s3) s3 = "%s %s from JournalDev - %d" % (s1, s2, 2018) print('String Concatenation using % Operator with Formatting =', s3) 
String Concatenation using % Operator = Hello World String Concatenation using % Operator with Formatting = Hello World from JournalDev - 2018 

String Concatenation using format() function

We can use string format() function for string concatenation and formatting too.

s1 = 'Hello' s2 = 'World' s3 = "<>-<>".format(s1, s2) print('String Concatenation using format() =', s3) s3 = " ".format(in1=s1, in2=s2) print('String Concatenation using format() =', s3) 
String Concatenation using format() = Hello-World String Concatenation using format() = Hello World 

Python String format() function is very powerful, using it just for concatenation of strings is not its proper use.

String Concatenation using f-string

If you are using Python 3.6+, you can use f-string for string concatenation too. It’s a new way to format strings and introduced in PEP 498 — Literal String Interpolation.

s1 = 'Hello' s2 = 'World' s3 = f' ' print('String Concatenation using f-string =', s3) name = 'Pankaj' age = 34 d = Data(10) print(f' age is and d=') 
String Concatenation using f-string = Hello World Pankaj age is 34 and d=Data[10] 

Python f-string is cleaner and easier to write when compared to format() function. It also calls str() function when an object argument is used as field replacement.

Conclusion

Python String formatting can be done in several ways. Use them based on your requirements. If you have to concatenate sequence of strings with a delimited, then use join() function. If some formatting is also required with concatenation, then use format() function or f-string. Note that f-string can be used with Python 3.6 or above versions.

You can checkout complete python script and more Python examples from our GitHub Repository.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Читайте также:  File index html gz is missing please upload it
Оцените статью