1

I have the following collection of items. I would like to add a comma followed by a space at the end of each item so I can create a list out of them. I am assuming the best way to do this is to form a string out of the items and then replace 3 spaces between each item with a comma, using regular expressions? I would like to do this with python, which I am new to.

179    181    191    193    197    199    211    223    227    229 
233    239    241    251    257    263    269    271    277    281 
283    293    307    311    313    317    331    337    347    349 
353    359    367    373    379    383    389    397    401    409 
419    421    431    433    439    443    449    457    461    463
4
  • ~I have these~ ... you mean they saved like this in a text file? Commented Apr 8, 2014 at 8:01
  • No I am writing a program and I need to make a list out of these items. I have copied the items from a website. I obviously do not want to manually place commas at the end of each item, I would rather a program do it for me. Commented Apr 8, 2014 at 8:05
  • "I have copied the items from a website" => So, the input are in a text file, no ? Commented Apr 8, 2014 at 8:09
  • I have copied the items into emacs text editor, in the same buffer I have written my program in. I am not sure how to write macros in emacs unfortunately. Commented Apr 8, 2014 at 8:12

2 Answers 2

1

Instead of a regular expression, how about this (assuming you have it in a file somewhere):

items = open('your_file.txt').read().split()

If it's just in a string variable:

items = your_input.split()

To combine them again with a comma in between:

print ', '.join(items)
Sign up to request clarification or add additional context in comments.

Comments

0
data = """179    181    191    193    197    199    211    223    227    229 
233    239    241    251    257    263    269    271    277    281 """

To get the list out of it:

lst = re.findall("(\d+)", data)
print lst

To add comma after each item, replace multiple spaces with , and space.

data = re.sub("[ ]+", ", ", data)
print data

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.