string to list conversion in python

后端 未结 6 2245
借酒劲吻你
借酒劲吻你 2021-01-13 05:25

I have a string.

s = \'1989, 1990\'

I want to convert that to list using python & i want output as,

s = [\'1989\', \'19         


        
6条回答
  •  青春惊慌失措
    2021-01-13 05:54

    Use the split method:

    >>> '1989, 1990'.split(', ')
    ['1989', '1990']
    

    But you might want to:

    1. remove spaces using replace

    2. split by ','

    As such:

    >>> '1989, 1990,1991'.replace(' ', '').split(',')
    ['1989', '1990', '1991']
    

    This will work better if your string comes from user input, as the user may forget to hit space after a comma.

提交回复
热议问题