0

I have python string as follows

mystring = "copy "d:\Progrm Files" "c:\Progrm Files\once up on a time""

how can I split this string to

mylist = [copy,d:\Progrm Files,c:\Progrm Files\once up on a time]

When I tried to use mysring.split(" ") the spaces Progrm Files and once up on a time are also getting split.

5
  • Youll have to use a regex to split Commented Jul 31, 2012 at 9:05
  • 5
    Your examples are invalid python; quotes inside quotes, and backslash escapes. Commented Jul 31, 2012 at 9:06
  • Now your code is invalid in a shell context; the shell will interpret the spaces in the same manner and not correctly interpret the command. Commented Jul 31, 2012 at 9:08
  • Hi Martijn iam getting a 'No closing quotation' error . Commented Jul 31, 2012 at 9:45
  • Your quoting is still quite seriously mucked up; you need to double check that your mystring is properly quoted for both python and the shell. Compare the example given in my answer with your own code. Commented Jul 31, 2012 at 9:46

2 Answers 2

9

You want to take a look at the shlex module, the shell lexer. It specializes in splitting command lines such as yours into it's constituents, including handling quoting correctly.

>>> import shlex
>>> command = r'copy "d:\Program Files" "c:\Program Files\once up on a time"'
>>> shlex.split(command)
['copy', 'd:\\Program Files', 'c:\\Program Files\\once up on a time']
Sign up to request clarification or add additional context in comments.

Comments

1

this regex catches what you want:

import re

mystring = "copy \"d:\Progrm Files\" \"c:\Progrm Files\once up on a time\""

m = re.search(r'([\w]*) ["]?([[\w]:\\[\w\\ ]+)*["]? ["]?([[\w]:\\[\w\\ ]+)*["]?', mystring)

print m.group(1)
print m.group(2)
print m.group(3)

>>> 
copy
d:\Progrm Files
c:\Progrm Files\once up on a time

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.