Concat item in list python

It's very useful for beginners to know why join is a string method.

It's very strange at the beginning, but very useful after this.

The result of join is always a string, but the object to be joined can be of many types (generators, list, tuples, etc).

.join is faster because it allocates memory only once. Better than classical concatenation (see, extended explanation).

Once you learn it, it's very comfortable and you can do tricks like this to add parentheses.

>>> ",".join("12345").join(("(",")"))
Out:
'(1,2,3,4,5)'

>>> list = ["(",")"]
>>> ",".join("12345").join(list)
Out:
'(1,2,3,4,5)'

This article describes how to concatenate strings in Python.

  • Concatenate multiple strings: +, += operator
  • Concatenate strings and numbers: +, += operator, str(), format(), f-string
  • Concatenate a list of strings into one string: join()
  • Concatenate a list of numbers into one string: join(), str()

Concatenate multiple strings: +, += operator

+ 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

+= operator

You can append another string to a string with the in-place operator, +=. The string on the right is concatenated after the string variable on the left.

s1 += s2
print(s1)
# aaabbb

If you want to add a string to the end of a string variable, use the += operator.

s = 'aaa'

s += 'xxx'
print(s)
# aaaxxx

Concatenate by writing string literals consecutively

If you write string literals consecutively, they are concatenated.

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

Even if there are multiple spaces or newlines with backslash \ (considered as continuation lines) between the strings, they are concatenated.

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

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

Using this, you can write long strings on multiple lines in the code.

  • Write a long string on multiple lines in Python

You cannot do this for string variables.

# s = s1 s2 s3
# SyntaxError: invalid syntax

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

The + operation between different types raises an error.

s1 = 'aaa'
s2 = 'bbb'

i = 100
f = 0.25

# s = s1 + i
# TypeError: must be str, not int

If you want to concatenate a string and a number, such as an integer int or a floating point float, convert the number to a string with str() and then use the + operator or += operator.

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

Use the format() function or the string method format() if you want to convert the number format, such as zero padding or decimal places.

  • string - Format Specification Mini-Language — Python 3.8.1 documentation

s = s1 + '_' + format(i, '05') + '_' + s2 + '_' + format(f, '.5f')
print(s)
# aaa_00100_bbb_0.25000

s = '{}_{:05}_{}_{:.5f}'.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 in 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

In Python 3.6 and later, you can also use a formatted string literal (f-string). It is even simpler than format().

  • 2. Lexical analysis - Formatted string literals — Python 3.9.4 documentation

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

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

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

  • Built-in Types - str - join() — Python 3.8.1 documentation

Call the join() method from 'String to insert' and pass [List of strings].

'String to insert'.join([List of strings])

If you use an empty string '', [List of strings] is simply concatenated, and if you use a comma ,, it makes a comma-delimited string. If a newline character \n is used, a newline will be inserted for 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 other iterable objects such as tuples can be specified as arguments of join().

Use split() to split a string separated by a specific delimiter and get it as a list. See the following article for details.

  • Split strings in Python (delimiter, line break, regex, etc.)

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

If you set a non-string list to join(), an error is raised.

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 (int or float) into a single string, apply the str() function to each element in the list comprehension to convert numbers to strings, then concatenate them with join().

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

It can be written as a generator expression, a generator version of list comprehensions. Generator expressions are enclosed in parentheses (), but you can omit () if the generator expression is the only argument of a function or method.

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

In general, generator expressions have the advantage of reduced memory usage compared with list comprehensions. However, since join() internally converts a generator into a list, there is no advantage to using generator expressions.

  • python - List vs generator comprehension speed with join function - Stack Overflow

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

  • List comprehensions in Python

How do you concatenate items in a list in python?

If you want to concatenate a list of numbers ( int or float ) into a single string, apply the str() function to each element in the list comprehension to convert numbers to strings, then concatenate them with join() . It can be written as a generator expression, a generator version of list comprehensions.

How do you concatenate elements in a list?

To concatenate the list without duplicates I have used set(list2) – set(list1) to find the difference between the two lists. The list and the new list are concatenated by using the “+” operator. The print(list) is used to get the output.

How do you merge all strings in a list in python?

Using join() method to concatenate items in a list to a single string. The join() is an inbuilt string function in Python used to join elements of the sequence separated by a string separator. This function joins elements of a sequence and makes it a string.

How do you join all elements in a list in python?

join() is an inbuilt string function in Python used to join elements of the sequence separated by a string separator. This function joins elements of a sequence and makes it a string..
Output: 1-2-3-4..
Output: geeks..
Output: '1S2S3S4S5' '1()2()3()4()5' 'G100e100e100k100s' 'Geek_For_Geeks'.