Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Splitting a string twice
#1
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?
Reply
#2
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.
Reply
#3
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'}
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  splitting file into multiple files by searching for string AlphaInc 2 816 Jul-01-2023, 10:35 PM
Last Post: Pedroski55
  splitting a string with 2 different delimiters Skaperen 4 2,650 Dec-30-2019, 04:49 AM
Last Post: BamBi25
  Splitting String into 2d list cclark135 2 2,756 Aug-26-2019, 01:46 PM
Last Post: ThomasL
  Strange behaviour while splitting string? naknak12 2 2,548 Feb-18-2019, 01:57 PM
Last Post: naknak12
  splitting a string by 2 characters Skaperen 8 8,820 Dec-27-2016, 06:14 AM
Last Post: wavic
  splitting a string numeically Skaperen 14 10,364 Oct-10-2016, 03:39 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020