Python join list with int

Python: Как преобразовать список в строку?

В этом коротком руководстве мы рассмотрим различные методы, которые можно использовать для преобразования списка Python в строку.

Зачем преобразовывать список Python в строку?

Преобразование списка Python в строку является обычным явлением, хотя наиболее распространенный случай использования, с которым я столкнулся, — это преобразование итерируемого объекта в строку, чтобы его можно было отобразить. Python предоставляет нам несколько способов преобразования списков Python в строку, эти методы не имеют конкретных ограничений для сравнения, и, следовательно, это сводится только к пониманию и удобству программистов этого метода.

Если это не так, я бы порекомендовал это решение, если вы новичок. Но не стесняйтесь пройти их все, если вам интересно их изучить.

Способы преобразования списка Python в строки

Используя join():

Наиболее распространенным и питоническим способом преобразования списка python в строку является использование метода join() . Он принимает итеративные объекты, последовательно присоединяет и возвращает их в виде строки. Однако значения в iterable должны иметь строковый тип данных, и в случае, если iterable содержит int, вы можете использовать второй метод.

Читайте также:  Крестики нолики си шарп код

Здесь string является разделителем

iterable — Любой итерируемый объект — список, кортежи, набор и т.д.

Код для преобразования списка Python в строку с помощью join():

flexiple = ["Hire", "the", "top", "freelancers"] print(" ".join(flexiple)) #Output - "Hire the top freelancers" 

Поскольку разделителем был пробел, строка содержит символы в списке, разделенные строкой.

Как упоминалось выше, попытка использовать итерацию, содержащую объект int , вернет typeerror . Следующее решение покажет вам, как это обойти.

flexiple = ["Hire", "the", "top", 10, "python","freelancers"] print(" ".join(flexiple)) 

Использование join() и map():

Поскольку методы join() принимают только строковые значения, мы используем map() для преобразования значений int в строку перед преобразованием списка python в строку. Методы map() выполняют определенную функцию для всех значений в итерации.

function — Конкретная функция, которую вы хотите выполнить

iterable — Итерируемый объект, содержащий значения

Таким образом, передавая функцию str() , которая преобразует объекты в строку, мы можем преобразовать значения типа int, а затем объединить их в строку.

Код для преобразования списка Python в строку с помощью map() :

flexiple = ["Hire", "the", "top", 10, "python","freelancers"] print(" ".join(map(str,flexiple))) #Output - "Hire the top 10 python freelancers" 

Использование цикла:

Третий метод преобразования списка Python в строку — это написать цикл и добавить каждую итерацию в строку. Я бы предложил этот метод, если вы новичок в Python и не знакомы с такими понятиями, как join() и map() т.д. Код может быть длиннее, но он будет более читабельным для новичка.

flexiple = ["Hire", "the", "top", 10, "python","freelancers"] f1 = "" for i in flexiple: f1 += str(i)+ " " print(f1) #Output = "Hire the top 10 python freelancers " 

Источник

Python join list with int

Last updated: Feb 18, 2023
Reading time · 3 min

banner

# Table of Contents

# Join a list of integers into a string in Python

To join a list of integers into a string:

  1. Use the map() function to convert the integers in the list to stings.
  2. Call the str.join() method on a string separator.
  3. Pass the map object to the join() method.
Copied!
my_list = [1, 2, 3, 4, 5] my_str = ', '.join(map(str, my_list)) print(my_str) # 👉️ "1, 2, 3, 4, 5"

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

Copied!
my_list = [1, 2, 3, 4, 5] # 👇️ ['1', '2', '3', '4', '5'] print(list(map(str, my_list)))

We simply passed each integer to the str() class to get a map object that only contains strings.

The string the join() method is called on is used as the separator between elements.

Copied!
my_list = [1, 2, 3, 4, 5] my_str = '-'.join(map(str, my_list)) print(my_str) # 👉️ "1-2-3-4-5"

If you don’t need a separator and just want to join the iterable’s elements into a string, call the join() method on an empty string.

Copied!
my_list = [1, 2, 3, 4, 5] my_str = ''.join(map(str, my_list)) print(my_str) # 👉️ "12345"

This approach also works if your list contains both strings and integers.

Copied!
my_list = [1, 'a', 2, 'b', 3, 'c', 4, 'd', 5] my_str = ', '.join(map(str, my_list)) print(my_str) # 👉️ "1, a, 2, b, 3, c, 4, d, 5"

Alternatively, you can pass a generator expression to the join() method.

# Join a list of integers into a string using a generator expression

This is a three-step process:

  1. Call the join() method on a string separator.
  2. Pass a generator expression to the join() method.
  3. On each iteration, pass the list item to the str() class to convert it to a string.
Copied!
my_list = [1, 2, 3, 4, 5] result = ', '.join(str(item) for item in my_list) print(result) # 👉️ "1, 2, 3, 4, 5"

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

We used a generator expression to convert each item to a string by passing it to the str() class.

# Join a list of integers into a string using a list comprehension

A list comprehension can also be used in place of a generator expression.

Copied!
my_list = [1, 2, 3, 4, 5] result = ', '.join([str(item) for item in my_list]) print(result) # 👉️ "1, 2, 3, 4, 5"

The code sample is very similar to the previous one, however, we used a list comprehension.

Copied!
my_list = [1, 2, 3, 4, 5] list_of_strings = [str(item) for item in my_list] print(list_of_strings) # 👉️ ['1', '2', '3', '4', '5'] print('-'.join(list_of_strings)) # 👉️ 1-2-3-4-5

On each iteration, we convert the current integer to a string and return the result.

# Join a list of integers into a string using a for loop

A for loop can also be used to convert the list of integers to a list of strings before joining them.

Copied!
my_list = [1, 2, 3, 4, 5] list_of_strings = [] for item in my_list: list_of_strings.append(str(item)) my_str = ', '.join(list_of_strings) print(my_str) # 👉️ "1, 2, 3, 4, 5"

We declared a new variable that stores an empty list and used a for loop to iterate over the original list.

On each iteration, we convert the current item to a string and append the result to the new list.

The last step is to join the list of strings with a separator.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Python Join List

Python Join List

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Python join list means concatenating a list of strings with a specified delimiter to form a string. Sometimes it’s useful when you have to convert list to string. For example, convert a list of alphabets to a comma-separated string to save in a file.

Python Join List

We can use python string join() function to join a list of strings. This function takes iterable as argument and List is an interable, so we can use it with List. Also, the list should contain strings, if you will try to join a list of ints then you will get an error message as TypeError: sequence item 0: expected str instance, int found . Let’s look at a short example for joining list in python to create a string.

vowels = ["a", "e", "i", "o", "u"] vowelsCSV = ",".join(vowels) print("Vowels are = ", vowelsCSV) 

Python join two strings

message = "Hello ".join("World") print(message) #prints 'Hello World' 

Why join() function is in String and not in List?

One question arises with many python developers is why the join() function is part of String and not list. Wouldn’t below syntax be more easy to remember and use?

There is a popular StackOverflow question around this, here I am listing the most important points from the discussions that makes total sense to me. The main reason is that join() function can be used with any iterable and result is always a String, so it makes sense to have this function in String API rather than having it in all the iterable classes.

Joining list of multiple data-types

names = ['Java', 'Python', 1] delimiter = ',' single_str = delimiter.join(names) print('String: '.format(single_str)) 

python join list multiple data types

Let’s see the output for this program: This was just a demonstration that a list which contains multiple data-types cannot be combined into a single String with join() function. List must contain only the String values.

Split String using join function

names = 'Python' delimiter = ',' single_str = delimiter.join(names) print('String: '.format(single_str)) 

python split string using join function

This shows that when String is passed as an argument to join() function, it splits it by character and with the specified delimiter.

Using split() function

Apart from splitting with the join() function, split() function can be used to split a String as well which works almost the same way as the join() function. Let’s look at a code snippet:

names = ['Java', 'Python', 'Go'] delimiter = ',' single_str = delimiter.join(names) print('String: '.format(single_str)) split = single_str.split(delimiter) print('List: '.format(split)) 

python split function, split string in python

Let’s see the output for this program: We used the same delimiter to split the String again to back to the original list.

Splitting only n times

The split() function we demonstrated in the last example also takes an optional second argument which signifies the number of times the splot operation should be performed. Here is a sample program to demonstrate its usage:

names = ['Java', 'Python', 'Go'] delimiter = ',' single_str = delimiter.join(names) print('String: '.format(single_str)) split = single_str.split(delimiter, 1) print('List: '.format(split)) 

python split count

Let’s see the output for this program: This time, split operation was performed only one time as we provided in the split() function parameter. That’s all for joining a list to create a string in python and using split() function to get the original list again.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

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