Concatenate string array 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.

Читайте также:  Показать больше показать меньше html

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.

Источник

Concatenate List of String in Python

Concatenate List of String in Python

  1. Use the join() Method to Convert the List Into a Single String in Python
  2. Use the map() Function to Convert the List of Any Data Type Into a Single String in Python
  3. Use the for Loop to Convert List Into a Single String in Python

This article will introduce methods to concatenate items in the Python list to a single string.

Use the join() Method to Convert the List Into a Single String in Python

The join() method returns a string in which the string separator joins the sequence of elements. It takes iterable data as an argument.

This method can be visualized as follow:

'separator'.join([ 'List','of',' string' ]) 

We call the join() method from the separator and pass a list of strings as a parameter. It returns the string accordingly to the separator being used. If a newline character \n is used in the separator, it will insert a new line for each list element. If one uses a comma , in the separator, it simply makes a commas-delimited string. The join() method returns a string in an iterable. A TypeError will be raised if any non-string values are iterable, including byte objects. An expression called generator expression is used to have all data types work for it.

For example, create a variable words_list and write some list elements on it. They are Joey , doesnot , share and food . Use a separator » » to call the join() method. Use the words_list variable as the argument in the function. Use the print() function on the whole expression.

In the example below, the join() function takes the words_list variable as an argument. Then, the separator » » is inserted between each list element. Finally, as an output, it returns the string Joey does not share food .

#python 3.x words_list = ['Joey', 'doesnot', 'share', 'food'] print(" ".join(words_list)) 

Use the map() Function to Convert the List of Any Data Type Into a Single String in Python

The map() function applies a specific function passed as an argument to an iterable object like list and tuple. The function is passed without calling it. It means there are no parentheses in the function. It seems the map() function would be a more generic way to convert python lists to strings.

This can be visualized as :

data : d1, d2, d3, . dn function: f map(function, data):  returns iterator over f(d1), f(d2), f(d3), . f(dn) 

For example, create a variable word_list and store some list items into it. They are Give , me , a , call , at and 979797 . Then, write a map() function and pass a function str and a variable words_list as arguments to the map() function. Write a join() function and take the map object as its argument. Use an empty string » » to call the join() function. Print the expression using the print() funtion.

The str function is called to all list elements, so all elements are converted to the string type. Then, space » » is inserted between each map object, and it returns the string as shown in the output section.

#python 3.x words_list = ['Give', 'me', 'a', 'call', 'at', 979797] print(" ".join(map(str, words_list))) 

Use the for Loop to Convert List Into a Single String in Python

We can use the for loop to get a single string from the list. In this method, we iterate over all the values, then append each value to an empty string. It is a straightforward process but takes more memory. We add a separator alongside the iterator to append in an empty string.

For example, create a variable words_list and store the list items. Next, create an empty string sentence . Use the for loop and use the variable word as an iterator. Use the str() method on the word and add it to the variable sentence . Then, add a «.» as the string to the function. After that, assign the expression to the variable sentence . Print the variable outside the loop.

In this example, the python list words_list contains a list of elements. The empty string variable sentence is used to append list elements on looping. Inside the loop, the str() method typecasts the elements to string, and «.» acts as a separator between each iterable item which gets appended to the empty string sentence .

#python 3.x words_list = ['Joey', 'doesnot', 'share', 'food'] sentence = "" for word in words_list:  sentence += str(word) + "." print(sentence) 

Источник

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