Python join list to one string

Преобразование списка в строку методом join

Метод join в Python отвечает за объединение списка строк с помощью определенного указателя. Часто это используется при конвертации списка в строку. Например, так можно конвертировать список букв алфавита в разделенную запятыми строку для сохранения.

Метод принимает итерируемый объект в качестве аргумента, а поскольку список отвечает этим условиям, то его вполне можно использовать. Также список должен состоять из строк. Если попробовать использовать функцию для списка с другим содержимым, то результатом будет такое сообщение: TypeError: sequence item 0: expected str instance, int found .

Посмотрим на короткий пример объединения списка для создания строки.

 
 
vowels = ["a", "e", "i", "o", "u"] vowels_str = ",".join(vowels) print("Строка гласных:", vowels_str)

Этот скрипт выдаст такой результат:

Почему join() — метод строки, а не списка?

Многие часто спрашивают, почему функция join() относится к строке, а не к списку. Разве такой синтаксис не было бы проще запомнить?

Это популярный вопрос на StackOverflow, и вот простой ответ на него:

Функция join() может использоваться с любым итерируемым объектом, но результатом всегда будет строка, поэтому и есть смысл иметь ее в качестве API строки.

Объединение списка с несколькими типами данных

Посмотрим на программу, где предпринимается попытка объединить элементы списка разных типов:

Источник

Python How to Join a List of Strings

Perhaps the most common question is how to join strings into one string separated by space.

  1. Specify a blank space as the separator strings.
  2. Call the join() method on the separator and the list of strings.

Here is how it looks in code.

words = ["This", "is", "a", "test"] joined = " ".join(words) print(joined)

If you were looking for a quick answer, there you have it!

However, there is a lot more when it comes to joining in Python. In this guide, you learn how joining/merging lists and other iterables work.

The join() method in Python

In Python, there is a built-in join() method that you can call on any string.

The join() method treats a string as a separator value for merging strings from an iterable.

Python join a list of strings

Syntax

Parameters

The iterable is the only parameter to the join() method.

It can be any iterable type in Python, that is a list, tuple, string, dictionary, or set.

The only restriction is that the elements in the iterable must be strings. Otherwise merging them into one long string fails.

Return Value

The join() method returns a single string with the joined values from the iterable.

For example, you can use the join() method to merge the elements of a list into one string.

Example

For instance, given a list of number strings, let’s join them and separate them by letter “x”:

nums = ["5", "3", "10"] joined = "x".join(nums) print(joined)
  • The string “x” is a separator string.
  • We call the join() method and pass in the list of strings.
  • This turns the list of strings into one long string separated by the separator string.

This is a neat approach to merging a bunch of values into one string.

Examples: Joining Iterables in Python

In Python, common iterable data types are:

When it comes to merging strings, you can pass any of these iterable types as an argument in the join() method call.

Let’s see examples of joining each of these iterable types.

Lists

At this point, joining lists of strings is nothing new.

nums = ["5", "3", "10"] joined = "x".join(nums) print(joined)

Tuples

A tuple is also an iterable type in Python.

Unlike lists, a tuple can be created simply by comma-separating elements.

For example, let’s join a tuple of strings into one sentence:

words = "Hello", "it", "is", "me" joined = " ".join(words) print(joined)

Strings

In Python, a string is iterable. It is a sequence of characters.

Because a string is iterable, you can pass it as an argument to the join() method.

This can be handy if you want to separate characters in a string by some value.

word = "Hello" joined = "-".join(word) print(joined)

As another example, let’s print each character of a string into a separate line:

word = "Hello" joined = "\n".join(word) print(joined)

Sets

In Python, a set is an unordered group of elements.

Because there is no order, the elements of a set are randomly picked up from the set.

For example, let’s merge a set of words together:

word = joined = "-".join(word) print(joined)

As you can see, the ordering is “incorrect”. This is because the notion of order is meaningless in a set as it is unordered.

Dictionaries

In Python, a dictionary is an iterable collection of key-value pairs.

This means you can also join a dictionary into a string.

But unlike other iterables, one dictionary element consists of two items — a key and a value.

How to Join Dictionary Keys

When joining a dictionary into a string, only the keys are taken into account.

d = joined = "-".join(d) print(joined)

How to Join Dictionary Values

Joining the values is straightforward. Instead of calling the join() method on a dictionary as-is, you need to call it on the values.

To join the dictionary values into a string:

  1. Specify a separator string.
  2. Access the dictionary values using the dict.values() method.
  3. Call the join method on the separator string by passing the dictionary values as an argument.
d = joined = "-".join(d.values()) print(joined)

Conclusion

Today you learned how to merge iterable elements into a single string in Python.

To recap, Python string implements the join() method. You can pass it an iterable argument. The join method loops through the elements of the iterable and combines them into a single string.

Источник

Python join() – How to Combine a List into a String in Python

Suchandra Datta

Suchandra Datta

Python join() – How to Combine a List into a String in Python

join() is one of the built-in string functions in Python that lets us create a new string from a list of string elements with a user-defined separator.

Today we'll explore join() and learn about:

  • join() syntax
  • how to use join() to combine a list into a string
  • how to combine tuples into a string with join()
  • how to use join() with dictionaries
  • when not to use join()

join() Syntax

  • it requires only one input argument, an iterable. An iterable is any object which supports iteration, meaning it has defined the __next__ and __iter__ methods. Examples of iterables are lists, tuples, strings, dictionaries, and sets.
  • join() is a built-in string function so it requires a string to invoke it
  • it returns one output value, a string formed by combining the elements in the iterable with the string invoking it, acting as a separator

How to Use join() to Combine a List into a String

We create a string consisting of a single occurrence of the | character, like this:

We can use the dir method to see what methods we have available to invoke using the s string object:

image-146

Among the various attributes and method names, we can see the join() method:

image-147

Let's create a list of strings:

country_names = ["Brazil", "Argentina", "Spain", "France"]

And now join the list elements into one string with the | as a separator:

country_names = ["Brazil", "Argentina", "Spain", "France"] s.join(country_names)

image-148

Here we see that join() returns a single string as output. The contents of the string variable invoking join() is the separator, separating the list items of the iterable country_names which forms the output. We can use any string we like as a separator like this:

s = "__WC__" s.join(country_names)

image-149

Using join() with lists of strings has lots of useful applications. For instance, we can use it to remove extra spaces between words. Suppose we have a sentence like the below where there are multiple spaces. We can use split() which will split on whitespace to create a list of words:

paragraph = "Argentina wins football world cup 2022 in a nail biting final match that led to a \ spectacular penalty shootout. Football lovers across the world hailed it as one of the most\ memorable matches." step1 = paragraph.split() print(step1)

Now we use join() using a single space to recreate the original sentence without the additional spaces in between:

image-156

How to Combine Tuples into a String with join()

Tuples are one of the built-in data types in Python which doesn't allow modifications once they're created – they're immutable. Tuples are comma separated lists of items enclosed in () like this:

t = ('quarter-final', 'semi-final', 'final')

We can combine tuple items together in the same way we were combining list items together using join() :

image-151

This is useful for cases where we need to use tuples – like storing large collections of items which need to be processed only once and then displaying the items in a comma-separated string.

How to Use join() with Dictionaries

Dictionaries are a mapping type in Python where we specify key value pairs for storage. Let's say we have this nested dictionary

We can use join() to extract a comma separated string with the keys and values like this:

column_values = ",".join(d["event"]["world cup"]["info"].keys()) row_values = ",".join(d["event"]["world cup"]["info"].values())

image-152

When Not to Use join()

join() won't work if you try to:

Let's look at some examples.

Iterables with elements that aren't strings

join() cannot be applied on sequences that contain items other than strings. So we won't be able to combine lists with numeric type elements. It would raise a TypeError like this:

names_and_numbers = ["Tom", 1234, "Harry"] ",".join(names_and_numbers)

image-153

Nested iterables

If we try to combine the values of a dictionary like this:

nested = ["Tom", "Harry", ["Jack", "Jill"]] ",".join(nested)

We'll get a TypeError, as join() is expecting a list of strings but received a list of a list of strings.

image-154

For such cases, flatten the list like this:

flatten = [ x for x in nested if isinstance(x, list)!=True] + \ [ e for each in nested for e in each if isinstance(each, list)==True]
[ x for x in nested if isinstance(x, list)!=True] 

checks if each item in nested is a list. If not, it adds it to a new list. And this:

[ e for each in nested for e in each if isinstance(each, list)==True]

creates a new 1D list element for any item in nested which is a list. Now we run join() like this:

nested = ["Tom", "Harry", ["Jack", "Jill"]] flatten = [ x for x in nested if isinstance(x, list)!=True] + \ [ e for each in nested for e in each if isinstance(each, list)==True] ",".join(flatten)

image-155

Wrapping Up

In this article, we learnt how to use the join() method on iterables like lists, dictionaries, and tuples. We also learned what sort of use-cases we can apply it on and situations to watch out for where join() would not work.

I hope you enjoyed this article and wish you a very happy and rejuvenating week ahead.

Источник

Читайте также:  Php execute as root
Оцените статью