- Преобразование списка в строку методом join
- Почему join() — метод строки, а не списка?
- Объединение списка с несколькими типами данных
- Python join() – How to Combine a List into a String in Python
- 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()
- Iterables with elements that aren't strings
- Nested iterables
- Wrapping Up
- List to String Python – join() Syntax Example
- What is a List in Python?
- What is a String in Python?
- How to Convert a Python List into a Comma-Separated String?
- How do you concatenate lists in Python?
- How do you convert a list to an array in Python?
- Can we convert a list into a dictionary in Python?
- How to Create a Dictionary from a List
- How to Create a Dictionary from Another Dictionary:
- There are so many awesome things you can do with Python Lists, Arrays, Dictionaries, and Strings
Преобразование списка в строку методом 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 join() – How to Combine a List into a String in Python
Suchandra Datta
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:
Among the various attributes and method names, we can see the join() method:
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)
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)
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:
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() :
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())
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)
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.
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)
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.
List to String Python – join() Syntax Example
Quincy Larson
Sometimes you want to convert your Python lists into strings. This tutorial will show you an example of how you can do this.
But first, let's explore the difference between the Python list data structure and the Python string data structure.
What is a List in Python?
In Python, a list is an ordered sequence of elements. Each element in a list has a corresponding index number that you can use to access it.
You can create a lists by using square brackets and can contain any mix of data types.
>>> exampleList = ['car', 'house', 'computer']
Note that I will be showing code from the Python REPL. The input I'm typing has >>> at the beginning of it. The output doesn't have anything at the beginning of it. You can launch this REPL by going into your terminal and typing python then hitting enter.
Once you've initialized a Python list, you can access its elements using bracket notation. Keep in mind that the index starts at zero rather than 1. Here's an example of inputs and outputs:
>>> exampleList[0] 'car' >>> exampleList[1] 'house' >>> exampleList[2] 'computer'
What is a String in Python?
A string is just a sequence of one or more characters. For example, 'car' is a string.
You can initialize it like this:
And then you can call your string data structure to see its contents:
How to Convert a Python List into a Comma-Separated String?
You can use the .join string method to convert a list into a string.
>>> exampleCombinedString = ','.join(exampleList)
You can then access the new string data structure to see its contents:
>>> exampleCombinedString 'car,house,computer'
So again, the syntax is [seperator].join([list you want to convert into a string]) .
In this case, I used a comma as my separator, but you could use any character you want.
Here. Let's join this again, but this time, let's add a space after the comma so the resulting string will be a bit easier to read:
>>> exampleCombinedString = ', '.join(exampleList) >>> exampleCombinedString 'car, house, computer'
How do you concatenate lists in Python?
There are a number of ways to concatenate lists in Python. The most common is to use the + operator:
>>> list1 = [1, 2, 3] >>> list2 = [4, 5, 6] >>> list1 + list2 [1, 2, 3, 4, 5, 6]
Another option is to use the extend() method:
>>> list1 = [1, 2, 3] >>> list2 = [4, 5, 6] >>> list1.extend(list2) >>> list1 [1, 2, 3, 4, 5, 6]
Finally, you can use the list() constructor:
>>> list1 = [1, 2, 3] >>> list2 = [4, 5, 6] >>> list3 = list1 + list2 >>> list3 [1, 2, 3, 4, 5, 6]
How do you convert a list to an array in Python?
One way to do this is to use the NumPy library.
Then run the np.array() method to convert a list to an array:
>>> a = np.array([1, 2, 3]) >>> print(a) [1 2 3]
Can we convert a list into a dictionary in Python?
Most definitely. First, let's create a dictionary using the built-in dict() function. Example dict() syntax:
d = dict(name='John', age=27, country='USA') print(d)
In this example, we create a dictionary object by using the dict() function. The dict() function accepts an iterable object. In this case, we use a tuple.
How to Create a Dictionary from a List
You can also create a dictionary from a list using the dict() function.
d = dict(zip(['a', 'b', 'c'], [1, 2, 3])) print(d)
Note that in this example, we used the zip() function to create a tuple.
How to Create a Dictionary from Another Dictionary:
You can create a dictionary from another dictionary. You can use the dict() function or the constructor method to do this.
There are so many awesome things you can do with Python Lists, Arrays, Dictionaries, and Strings
I am really just scratching the surface here. If you want to go way deeper, and apply a lot of these methods and techniques on real world projects, freeCodeCamp.org can help you.
If you want to learn more about programming and technology, try freeCodeCamp's core coding curriculum. It's free.
Quincy Larson
The teacher who founded freeCodeCamp.org.
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)
Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons - all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.