Home > Backend Development > Python Tutorial > Python program to convert list of strings to comma separated strings

Python program to convert list of strings to comma separated strings

WBOY
Release: 2023-09-09 21:25:03
forward
1006 people have browsed it

Python program to convert list of strings to comma separated strings

Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and UnixShell, as well as many other scripting languages.

Now, we know that this post is about converting a list of strings into comma separated strings. Before delving further, it is necessary to understand strings and lists in Python in detail. Let’s continue with the topic and learn about them in detail. Start with a string.

What is a string?

Python strings are character sequences, which means they are ordered collections of characters.

"This is a string."
'This is also a string.'
Copy after login

Strings in Python are byte arrays representing Unicode characters. Python strings are "immutable", which means they cannot be changed after they are created. This means that its internal data elements, i.e. characters, can be accessed but cannot be replaced, inserted or deleted for input and output. String is a data structure. A data structure is a composite unit made up of several other pieces of data. A string is a sequence of zero or more characters.

The length of a string is the number of characters it contains. Python's len() function is used to return the length of a string.

grammar

len(str)
Copy after login

Example

len("WELCOME")
Copy after login

Output

7
Copy after login

Each character occupies a position in the string. The character positions of the string are numbered from left to right, starting from 0 and ending with the length of the string minus 1. Now, moving on to the topic of lists.

What is a list?

A list is a collection of items arranged in a specific order. You can create a list containing letters of the alphabet and numbers 0-9. In Python, square brackets ([]) represent a list, and the elements in the list are separated by commas.

Example

bicycles = ['trek', 'Cannondale', 'redline', 'specialized']
print(bicycles)
Copy after login

Output

['trek', 'Cannondale', 'redline', 'specialized']
Copy after login

A list is a value that contains multiple values ​​in an ordered sequence. The term list value refers to the list itself (which is a value that can be stored in a variable or passed to a function like any other value), not the values ​​within the list value. List values ​​look like this: ['cat', 'bat', 'rat', 'elephant']. Values ​​within a list are also called items. Items are separated by commas (that is, they are separated by commas).

Here we will learn how to change a string into a comma separated string. It's important to remember that the given string can also be a list of strings.

Convert Python list to comma separated string

When we convert a list of strings to a comma-separated string, it results in a string where each element in the list is separated by commas.

For example, if we convert ["my", "name", "is", "Nikita"] to a comma-separated string, we will get "my, name, is, Nikita".

Use join() function

Iterable components are composed of the join() function , which also returns a string. The character used to separate string elements must be specified.

Here, we need to create a comma separated string, so we will use comma as delimiter.

Example

The following program creates a list and joins them into a comma-separated string using the join() function.

List = ["Apple", "Banana", "Mango", "Orange"]
String = ', '.join(List)
print("List of String:")
print(List)
print("Comma Separated String:")
print(String)
Copy after login

Output

List of String:
['Apple', 'Banana', 'Mango', 'Orange']
Comma Separated String:
Apple, Banana, Mango, Orange
Copy after login

The above method only applies to string lists.

To handle lists of integers or other elements, we can use list comprehension and str() function. We can use a for loop to quickly run through the elements of a list comprehension in a row, and then use the str() function to convert each element to a string.

Example

In the following program, a list of strings is created and stored in the variable List. Then create a new string by concatenating each element in the list using commas as separators and store it in the variable String.

List = ['235', '3754', '856', '964']
String = ', '.join([str(i) for i in List])
print("List of String:")
print(List)
print("Comma Separated String:")
print(String)
Copy after login

Output

List of String:
['235', '3754', '856', '964']
Comma Separated String:
235, 3754, 856, 964
Copy after login
Copy after login

Using the map() function, we can also eliminate list comprehensions. You can use the map() function to convert all elements of a list to strings by applying the str() function to each element of the list.

Example

Using the map() function, we can also eliminate the list comprehension. You can use the map() function to convert all elements of a list to strings by applying the str() function to each element of the list.

List = ['235', '3754', '856', '964']
String = ', '.join(map(str,List))
print("List of String:")
print(List)
print("Comma Separated String:")
print(String)
Copy after login

Output

List of String:
['235', '3754', '856', '964']
Comma Separated String:
235, 3754, 856, 964
Copy after login
Copy after login

Using StringIO module

StringIO object is equivalent to a file object, but it works with text in memory. It can be imported directly into Python 2 by leveraging the StringIO module. It is kept in the io module in Python 3.

Example

To write a list of comma separated rows to a CSV file in a StringIO object, we can use the csv.writerow() function. To do this we must first create a csv.writer object. Using the getvalue() function we can store the contents of this object in a string.

import io
import csv
List = ['235', '3754', '856', '964']
String_io = io.StringIO()
w = csv.writer(String_io)
w.writerow(List)
String = String_io.getvalue()
print("List of String:")
print(List)
print("Comma Separated String:")
print(String)
Copy after login

Output

List of String:
['235', '3754', '856', '964']
Comma Separated String:
235,3754,856,964
Copy after login

We can also use the unpacking operator with the print() function. The unpacking operator * unpacks all elements of the iterable object and saves them in a StringIO object via the file parameter in the print() function.

示例

使用值 8、9、4 和 1 创建一个列表。然后创建一个 StringIO 对象 String_io,允许将字符串视为文件。该列表打印为 StringIO 对象,其中 file=String_io、sep=',' 和 end=''。这用逗号分隔列表中的每个元素,并且不会在行尾添加新行或字符。存储在 string_io 中的字符串由 getvalue() 方法检索并存储在名为“String”的变量中。

import io
List = [8,9,4,1]
String_io = io.StringIO()
print(*List, file=String_io, sep=',', end='')
String = String_io.getvalue()
print("List of String:")
print(List)
print("Comma Separated String:")
print(String)
Copy after login

输出

List of String:
[8, 9, 4, 1]
Comma Separated String:
8,9,4,1
Copy after login

结论

在本文中,我们讨论了将字符串列表转换为逗号分隔字符串的不同方法。

The above is the detailed content of Python program to convert list of strings to comma separated strings. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template