PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 30, 2022

[FIXED] How to create a list in python when the elements contain commas

 August 30, 2022     csv, list, python     No comments   

Issue

How do I create a list of strings in python where the strings can contain commas such that the interpreter doesn't break on commas prematurely.

I am reading in a template csv file, created by MSExcel. The contents are 2 columns: col1 = color, col2 = a sentence that can contain a comma. The content is as follows:

Light Green,"Matches type, instance, etc."
Red,Happens in BD10 but not BD20
Blue,"Instance and time matches, type doesn't match"
Yellow,Caught on replay

When I read in and output what was read, it breaks the input line on all commas.

#my code snippet, please excuse any typos during sanitization
with open('outfile.csv','r') as infile:
   blah = infile.readlines()
   for i in blah:
      line = i.strip().split(",")
      print line

My output:
['Light Green', '"Matches type', ' instance', ' etc."']
['Red', 'Happens in BD10 but not BD20']
['Blue', '"Instance and time matches', ' type doesn\'t match"']
['Yellow', 'Caught on replay']

How do I tell python to ignore commas when it's within "" and break at commas all other times?


Solution

Stop the split after the first comma:

line = i.strip().split(",", 1)


Answered By - Brent Washburne
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing