Python concatenate list and str

About «can only concatenate str (not “list”) to str» in Python

As you probably know, programming languages are either strongly typed or loosely typed. Strongly-typed programming languages such as Python have a strict type system to help the programmer avoid data-type-related mistakes — meaning some operations aren’t allowed on some data types. For instance, you can’t divide 20 by ‘4’ (because ‘4’ is a string value) — depending on the operation, the error messages might vary. Whenever you declare a variable like name = ‘John’ , as a dynamically-typed language, Python determines the data type to be a string. Now, if you try to concatenate it with a list, you’ll get the «TypeError: can only concatenate str (not «list») to str» error.

How to fix TypeError: can only concatenate str (not «list») to str

  1. Convert the list into a string value with the str.join() method
  2. Access list items individually
  3. Use print() with multiple arguments — ideal for debugging
  4. Use an f-string
  5. Use printf-style formatting
Читайте также:  Работать со словарем питон

Convert the list into a string with the str.join() method: If you want to concatenate the items of a list to a string value, use str.join() like so:

books = ['Fluent Python', 'Head First Python'] output = 'Resources: ' + ', '.join(books) print(output) # output: Resources: Fluent Python, Head First Python 

In the above code, we separate the list items by a comma. Please note we call the join method on the separator string (in this case: ‘, ‘ ). It seems weird, but that’s how it works!

Access list items individually: Sometimes, you need to concatenate a single list item with a string value, but you use the whole list object by mistake.

In that case, you need to access the item by its index:

books = ['Fluent Python', 'Head First Python'] output = 'Top Pick: ' + books[1] print(output) # output: Top Pick: Head First Python 

Use print() with multiple arguments — ideal for debugging: If you’re concatenating a string with a list and readability isn’t a concern, you can pass the string and the list as separate arguments to the print() function.

All the positional arguments passed to the print() function are automatically converted to strings — like how str() works.

books = ['Fluent Python', 'Head First Python'] print('Fetched these books:', books) # output: Fetched these books: ['Fluent Python', 'Head First Python'] 

As you can see, the print() function outputs the arguments separated by a space. You can also change the separator via the sep keyword argument.

Use an f-string: Formatted string literals (a.k.a f-strings) are a robust way of formatting strings because they allow you to use Python expressions directly in string values (in a pair of curly brackets <> ).

You create an f-string by prefixing it with f or F and writing expressions inside curly braces:

books = ['Fluent Python', 'Head First Python'] print(f'Fetched these books: books>') # output: Fetched these books: ['Fluent Python', 'Head First Python'] 

Additionally, you can join the list items before using it in the string:

books = ['Fluent Python', 'Head First Python'] book_list = ', '.join(books) print(f'Fetched these books: book_list>') # output: Fetched these books: Fluent Python, Head First Python 

Use printf-style formatting: In the old string formatting (a.k.a printf-style string formatting), we use the % (modulo) operator to generate dynamic strings (string % values).

The string operand is a string literal containing one or more placeholders identified with % , while the values operand can be a single value or a tuple of values.

books = ['Fluent Python', 'Head First Python'] print('Fetched these books: %s' % books) # output: Fetched these books: ['Fluent Python', 'Head First Python'] 

When using the old-style formatting, check if your format string is valid. Otherwise, you’ll get another type error: not all arguments converted during string formatting.

Alright, I think that does it! I hope this quick guide helped you fix your problem.

❤️ You might like:

Источник

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.

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) 

Источник

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