Combining strings in python

Concatenate strings in Python (+ operator, join, etc.)

This article explains how to concatenate strings or a list of strings in Python.

Concatenate multiple strings: + , +=

The + operator

You can concatenate string literals ( ‘. ‘ or «. » ) and string variables with the + operator.

s = 'aaa' + 'bbb' + 'ccc' print(s) # aaabbbccc s1 = 'aaa' s2 = 'bbb' s3 = 'ccc' s = s1 + s2 + s3 print(s) # aaabbbccc s = s1 + s2 + s3 + 'ddd' print(s) # aaabbbcccddd 

The += operator

You can append a string to an existing string with the += operator. The string on the right is concatenated after the string variable on the left.

s1 = 'aaa' s2 = 'bbb' s1 += s2 print(s1) # aaabbb s = 'aaa' s += 'xxx' print(s) # aaaxxx 

Concatenate consecutive string literals

If you write string literals consecutively, they are automatically concatenated.

s = 'aaa''bbb''ccc' print(s) # aaabbbccc 

Even if multiple spaces, newlines, or backslashes \ (used as continuation lines) are present between the strings, they will still be concatenated.

s = 'aaa' 'bbb' 'ccc' print(s) # aaabbbccc s = 'aaa'\ 'bbb'\ 'ccc' print(s) # aaabbbccc 

This approach can be handy when you need to write long strings over multiple lines of code.

Читайте также:  Java событие при нажатии клавиши

Note that this automatic concatenation cannot be applied to string variables.

# s = s1 s2 s3 # SyntaxError: invalid syntax 

Concatenate strings and numbers: + , += , str() , format() , f-string

The + and += operators and str()

The + operation between different types results in an error.

s1 = 'aaa' s2 = 'bbb' i = 100 f = 0.25 # s = s1 + i # TypeError: must be str, not int 

To concatenate a string and a number, such as an integer int or a floating point number float , you first need to convert the number to a string with str() . Then, you can use the + or += operator to concatenate.

s = s1 + '_' + str(i) + '_' + s2 + '_' + str(f) print(s) # aaa_100_bbb_0.25 

format() and f-string

If you need to adjust the format, such as zero-padding or decimal places, the format() function or the str.format() method can be used.

s1 = 'aaa' s2 = 'bbb' i = 100 f = 0.25 s = s1 + '_' + format(i, '05') + '_' + s2 + '_' + format(f, '.5f') print(s) # aaa_00100_bbb_0.25000 s = '<>_ _<>_ '.format(s1, i, s2, f) print(s) # aaa_00100_bbb_0.25000 

Of course, it is also possible to embed the value of a variable directly into a string without specifying the format, which is simpler than using the + operator.

s = '<>_<>_<>_<>'.format(s1, i, s2, f) print(s) # aaa_100_bbb_0.25 

For more information about format() and str.format() , including format specification strings, see the following article.

In Python 3.6 or later, you can also use f-strings for a more concise syntax.

s = f's1>_i:05>_s2>_f:.5f>' print(s) # aaa_00100_bbb_0.25000 s = f's1>_i>_s2>_f>' print(s) # aaa_100_bbb_0.25 

Join a list of strings into one string: join()

You can concatenate a list of strings into a single string with the string method, join() .

Call the join() method from ‘STRING_TO_INSERT’ and pass [LIST_OF_STRINGS] .

'STRING_TO_INSERT'.join([LIST_OF_STRINGS]) 

Using an empty string » will simply concatenate [LIST_OF_STRINGS] , while using a comma , creates a comma-delimited string. If a newline character \n is used, a newline will be inserted between each string.

l = ['aaa', 'bbb', 'ccc'] s = ''.join(l) print(s) # aaabbbccc s = ','.join(l) print(s) # aaa,bbb,ccc s = '-'.join(l) print(s) # aaa-bbb-ccc s = '\n'.join(l) print(s) # aaa # bbb # ccc 

Note that join() can also take other iterable objects, like tuples, as its arguments.

Use split() to split a string separated by a specific delimiter into a list. See the following article for details.

Join a list of numbers into one string: join() , str()

Using join() with a non-string list raises an error.

l = [0, 1, 2] # s = '-'.join(l) # TypeError: sequence item 0: expected str instance, int found 

If you want to concatenate a list of numbers, such as int or float , into a single string, convert the numbers to strings using list comprehension with str() . Then, concatenate them using join() .

s = '-'.join([str(n) for n in l]) print(s) # 0-1-2 

You can also use a generator expression, which is similar to list comprehensions but creates a generator instead. Generator expressions are enclosed in parentheses () . However, if the generator expression is the only argument of a function or method, you can omit the parentheses.

s = '-'.join((str(n) for n in l)) print(s) # 0-1-2 s = '-'.join(str(n) for n in l) print(s) # 0-1-2 

While generator expressions generally use less memory than list comprehensions, this advantage is not significant with join() , which internally converts a generator to a list.

See the following article for details on list comprehensions and generator expressions.

Источник

Python Concatenate Strings – How to Combine and Append Strings in Python

Ihechikara Vincent Abba

Ihechikara Vincent Abba

Python Concatenate Strings – How to Combine and Append Strings in Python

When you’re learning a programming language, you’re likely to come across a data type called a string. A string usually contains a series of characters nested in quotation marks that can be represented as a text.

In this article, we will talk about string concatenation in Python. This is the process of joining/adding one string to another. For example, the concatenation of «freeCode» and «Camp» is «freeCodeCamp».

String concatenation is important when working with two or more separate variables (strings) that are combined to form a much larger string.

This also enables you have separate units of a string even after combining them, just in case you need to use one string variable somewhere else in your code and not the entire string.

How to Concatenate Strings in Python

To concatenate string in Python, we use the + operator to append the strings to each other. Here is an example:

x = "Happy" y = "Coding" z = x + y print(z) #HappyCoding

In the code above, we created two variables ( x and y ) both containing strings – «Happy» and «Coding» – and a third variable ( z ) which combines the two variables we created initially.

We were able to combine the two variables by using the + operator. Our output after this was HappyCoding . If you were to reverse the order during concatenation by doing this: z = y + x then we would get CodingHappy printed to the console.

How to Add Spaces Between Concatenated Strings

You might notice that there was no space between the variables when printed. Here’s how we can add spaces between concatenated strings:

x = "Happy" y = "Coding" z = x + " " + y print(z) # Happy Coding

You’ll notice that there is a space between the quotation marks. If you omit the space then the strings will still be closely joined together.

You can also add spaces at the end of a string when it is created and it will be applied when printed. Here’s how you’d do that:

x = "Happy " y = "Coding" z = x + y print(z) #Happy Coding

How to Create Multiple Copies of a String Using the * Operator

When we use the * operator on a string, depending on value passed, we create and concatenate (append) copies of the string. Here is an example:

x = "Happy" y = x * 3 print(y) # HappyHappyHappy

Using the * operator, we duplicated the value of the string «Happy» three times with the three printed values closely packed together.

If we were to add a space at the end of the string, then the strings will be separated. That is:

x = "Happy " y = x * 3 print(y) # Happy Happy Happy

Conclusion

In this article, we learned how to combine strings in Python through concatenation.

Thank you for reading and happy coding!

Источник

Python String Concatenation

Use the + character to add a variable to another variable:

Example

Example

Merge variable a with variable b into variable c :

Example

To add a space between them, add a » » :

For numbers, the + character works as a mathematical operator:

Example

If you try to combine a string and a number, Python will give you an error:

Example

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Python String Concatenation [6 Easy Ways]

The + operator concatenates two or more strings. When used between two strings, it combines them into a single string.

Example

string1 = "John" string2 = "Wick4" movie = string1 + " " + string2 print(movie)

Method 2: Using the join() method

The string join() method concatenates elements of an iterable (e.g., list, tuple) using the string on which it is called a delimiter.

Example

words = ["John", "Wick4"] delimiter = " " result = delimiter.join(words) print(result)

Method 3: String Concatenation using % Operator

We can use the % operator for string formatting, and it can also be used for string concatenation.

Example

data1 = "Hello" data2 = "World" print("% s % s" % (data1, data2))

Method 4: Using the format() function

The string.format() method allows multiple substitutions and value formatting. It concatenates elements within a string through positional formatting.

Example

data1 = "Fire" data2 = "Base" # format function is used here to # combine the string print("<> <>".format(data1, data2)) # store the result in another variable var3 = "<> <>".format(data1, data2) print(var3) 

Method 5: Using (, comma)

The “,” is a great alternative to string concatenation using “+”. when you want to include single whitespace. Use a comma to combine data types with single whitespace in between.

Example

data1 = "Fire" data2 = "Base" print(data1, data2)

Method 6: 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.

Example

data1 = "Fire" data2 = "base" s3 = f'' print('String Concatenation using f-string:', s3) 
String Concatenation using f-string: Firebase

Источник

Оцените статью