Search code examples
python-2.7splituser-input

How to take comma as text in comma separated text in python


Hi I'm new to python and I wanted to know how enter comma as text in comma separated string in python

for eg

Text=raw_input("Enter the symbols").split(",")

Input:

A, b, c, d, e,",",f

Output:

["A","b","c","d",",","f"]


Solution

  • The problem here is the split statement, it literally matches the delimiter (, in this case).

    Doing something like this takes proper parsing, e.g. using the csv module

    import csv
    
    Text = raw_input("Enter the symbols:")
    reader = csv.reader([Text], delimiter=',')
    symbols = next(reader)
    print(symbols)
    

    Update: when scanning for symbols, doubles and "" are probably not valid.

    For instance, a,a,b,,"," would give ['a', 'a', 'b', '', ',']

    So this extension cleans symbols as well:

    import csv
    
    Text = raw_input("Enter the symbols:")
    reader = csv.reader([Text], delimiter=',')
    symbols = set(data for data in next(reader) if data)
    print(symbols)
    

    Note: the output is a set and might be empty.