Python Forum

Full Version: Splitting a string twice
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I am splitting a string at a comma and then at a colon. Although this is working I think there must be a nice way.

            cn_only = computer_attributes.split(',')[0]
            cn_only = cn_only.split(':')[1]
            timestamp_only = computer_attributes.split(',')[2]
            timestamp_only = timestamp_only.split(':')[1]
            os_only = computer_attributes.split(',')[1]
            os_only = os_only.split(':')[1]
This there a way to do each of these in one line?
I don't know if it will work, but you could try:
cn_only = (computer_attributes.split(',')[0]).split(':')[1]
Let me know, I'm curious.
I am guessing the required output from the OP code (and can be wrong):

>>> s = 'a:1, b:2, c:3'
>>> [chunk.split(':') for chunk in s.split(', ')]
[['a', '1'], ['b', '2'], ['c', '3']]
>>> [chunk.split(':')[1] for chunk in s.split(', ')]
['1', '2', '3']
>>> dict(zip('cn timestamp, os'.split(), [chunk.split(':')[1] for chunk in s.split(', ')]))
{'cn': '1', 'timestamp,': '2', 'os': '3'}