Hướng dẫn comma in python

You can use the str.split method.

Nội dung chính

  • Do Not Forget to Handle Empty Strings
  • How to Convert a Comma-Delimited String with Integers and Characters to a List
  • Further Reading
  • How do you add Comma Separated Values in Python?
  • How do you make a comma
  • How do you convert comma

Nội dung chính

  • Do Not Forget to Handle Empty Strings
  • How to Convert a Comma-Delimited String with Integers and Characters to a List
  • Further Reading
  • About the author
  • How do you add Comma Separated Values in Python?
  • How do you make a comma
  • How do you convert comma
>>> my_string = 'A,B,C,D,E'
>>> my_list = my_string.split(",")
>>> print my_list
['A', 'B', 'C', 'D', 'E']

If you want to convert it to a tuple, just

>>> print tuple(my_list)
('A', 'B', 'C', 'D', 'E')

If you are looking to append to a list, try this:

>>> my_list.append('F')
>>> print my_list
['A', 'B', 'C', 'D', 'E', 'F']

To convert comma-delimited string to a list in Python, split the string with the str.split() method:

string = "A,B,C,D,E,F,G"

string_list = string.split(",")

print(string_list)

Output:

['A', 'B', 'C', 'D', 'E', 'F', 'G']

Assuming the string is not empty.

Do Not Forget to Handle Empty Strings

Using the above approach on an empty string returns a list with one empty string. But this is not what you would expect. Instead, the list should be empty if the string is empty.

To handle the case of an empty string, slightly modify the previous approach:

string = ""

string_list = string.split(",") if string else []

print(string_list)

Output:

[]

Let’s also take a look at what you can do if the string contains both strings and integers.

How to Convert a Comma-Delimited String with Integers and Characters to a List

If you have a string that represents both integers and strings, you may want to

  • Keep the strings as strings.
  • Cast the integer strings to real integers.

To do this, you can use a regular for loop like this:

string = "1,B,C,3,E,5,6"

string_list = []

for item in string.split(","):
    if item.isdigit():
        string_list.append(int(item))
    else:
        string_list.append(item)

print(string_list)

Output:

[1, 'B', 'C', 3, 'E', 5, 6]

Or you can use a list comprehension to shorten the loop:

string = "1,B,C,3,E,5,6"

string_list = [int(e) if e.isdigit() else e for e in string.split(",")]

print(string_list)

Output:

[1, 'B', 'C', 3, 'E', 5, 6]

Conclusion

Today you learned how to convert a comma-delimited string to a list in Python.

Thanks for reading. I hope you find it useful!

Happy coding!

Further Reading

List Comprehensions in Python

Python Tips and Tricks

Strings in Python are a sequence of characters or a collection of bytes. However, Python does not support character data type but it considers a single character a string with a span of 1. We use quotes to generate strings in Python. Also, we use square brackets to access string elements in python. Python strings are absolute. Now, let’s discuss how to create a Python list of comma-separated strings.

The list in Python is indexed in order and starts from 0. The most versatile thing about a list is that every item in the list has its place. If you convert a list into a comma-separated string, then your resultant string contains an element of the list that is separated by a comma. Come, let’s elaborate on it with the help of illustrations. We use the Spyder compiler to describe the working of the python list to a comma-separated string.

Example 1

In this example, we use the join () + str () function to make a python list separated by a comma. This is a very simple and easy process. Now let’s check how the code works in Python. At first, launch Spyder IDE in Windows 10. To launch it simply type ‘Spyder’ in your Windows PC search bar and then click open. Press the key combination ‘Ctrl+Shift+N’ to create a new file. Once done, write a Python code to elaborate on how to make a Python list to a comma-separated string.

At first, we initialize a list and use the print function to print original values in the list. Then we initialize a ‘delim’. After initializing the delimiter, we use the map function to convert every list item into a string. We can then use the join function to add a comma at the end of each value, after altering each value to a string. At last, we use the print function which prints the output on the console screen. The code is shown in textual form. Also, we have attached a screenshot as well.

Original_list = [6, "Hfh", 9, "is", "good", 2]

print("Our list is : " + str(Original _list))

delim = "*"

temp = list(map(str, Original _list))

result = delim.join(temp)

print("List to comma separated string: " + str(result))

Hướng dẫn comma in python

After you successfully write the Python code, now it is time to save your code file with the ‘.py’ extension as below. The file name may be changed in your illustration.

Now, run the file or simply use the “F9” shortcut key to check the output of a Python list to a comma-separated string. The output is displayed in the appended image.

Example 2

In our second example, we use the loop + str () function to find a python list to a comma-separated string. Now, let’s check how the program works. Let’s move to the Spyder compiler in Windows 10 and select a new empty file or use the same file “StringList1.py”. We use the same code file “StringList1.py” and made changes to it. We use another way to demonstrate the working of a Python list to a comma-separated string.

At first, we initialize a list and use the print function to print original values in the list. Then we use a loop to add a comma at the end of each value, after altering each value to a string. At last, we use the print function which prints the output on the console screen. The code is shown in textual form. Also, we have attached a screenshot as well.

string_list = [8, "Hfh", 0, "is", "good", 2]

print("Our list is : " + str(string _list))

delim = "*"

result = ''

for ele in string_list:

Result = result + str(ele) + delim

print("List to comma separated string: " + str(result))

Again, save the “StringList1.py” file for further execution. Then again, build and run the code or simply use the F9 key to check the output of a Python list to a comma-separated string. After compiling the above program, you will get the desired output. The output is displayed in the appended image.

Conclusion

In this tutorial, we discussed the importance of Python string and how to make a Python list to comma separated string using the Spyder compiler. We have listed two different and unique ways to implement our article. You can use any other method to implement comma-separated strings in Python language.

Hello, I am a freelance writer and usually write for Linux and other technology related content

How do you add Comma Separated Values in Python?

Use str..

a_list = ["a", "b", "c"].

joined_string = ",". join(a_list) Concatenate elements of `a_list` delimited by `","`.

print(joined_string).

How do you make a comma

split() method to convert a comma-separated string to a list, e.g. my_list = my_str. split(',') . The str. split() method will split the string on each occurrence of a comma and will return a list containing the results.

How do you convert comma

Input a comma - separated string using raw_input() method. Split the elements delimited by comma (,) and assign it to the list, to split string, use string. split() method. The converted list will contains string elements.

Tải thêm tài liệu liên quan đến bài viết Hướng dẫn comma in python