1

I want to split a string with both ", " and ",". So I have to make a program in which I take input from the user, which is like:- 4, 16, 8, etc. and then double each the number. This is what I have written so far:-

def main():
    a = []
    def Convert(string):
        li = list(string.split(", "))
        return li

    def double(lst):
        for i, x in enumerate(lst):
            x = int(x)
            x = x+x
            a.append(x)

    str1 = input()
    n = Convert(str1)
    f = double(n)
    print(a)

     

if __name__ == "__main__":
    main()

#Results
inp = 14, -4, 8
out = 28, -8, 16

inp = 14,-4,8
out = error

That's why I want to make it so that it will split with ", " and ",". Pls help

4 Answers4

1

Instead of that, you can do this:

def split_list(val):
    nums=val.split(",")
    return ', '.join(str(int(num.strip())*2) for num in nums)
x=input("Enter numbers: ")
print(split_list(x))
1

To split string using multiple delimeters use re modules split method.

>>> import re
>>> re.split(',|,\s', "14,-4,8")
['14', '-4', '8']
>>> re.split(',|,\s', "14, -4, 8")
['14', ' -4', ' 8']

The split method returns list with separated values according to the delimiters you specified.

ram4279
  • 31
  • 3
0

You can replace space with null and then split on ',' like follow:-

def main():
    a = []
    def Convert(string):
        string = string.replace(" ","")
        li = list(string.split(","))
        return li

    def double(lst):
        for i, x in enumerate(lst):
            x = int(x)
            x = x+x
            a.append(x)

    str1 = input()
    n = Convert(str1)
    f = double(n)
    print(a)

     

if __name__ == "__main__":
    main()
-1

You can try this

def main():
    a = []
    def Convert(string):
        li = list(string.split("," or ", "))
        return li

    def double(lst):
        for i, x in enumerate(lst):
            x = int(x)
            x = x+x
            a.append(x)

    str1 = input()
    n = Convert(str1)
    f = double(n)
    print(a)

if __name__ == "__main__":
    main()

Simply using or for split should work in your case

Manu
  • 57
  • 3