拆分字符串在python
问题描述:
我有Python字符串如下拆分字符串在python
mystring = "copy "d:\Progrm Files" "c:\Progrm Files\once up on a time""
我哪有这个字符串分割到
mylist = [copy,d:\Progrm Files,c:\Progrm Files\once up on a time]
当我试图用mysring.split(" ")
空间Progrm Files
和once up on a time
也越来越分裂。
答
你想看看shlex
module,shell的词法分析器。它擅长将诸如你的命令行分解为它的组成部分,包括正确处理引用。
>>> 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']
+0
谢谢martijn – tjdoubts 2012-07-31 13:39:11
答
这个表达式捕捉你想要的东西:
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
youll必须使用正则表达式来分割 – Paranaix 2012-07-31 09:05:58
你的例子是无效的蟒蛇;引号内的引号和反斜杠转义。 – 2012-07-31 09:06:02
现在,您的代码在shell上下文中无效; shell将以相同的方式解释空格,并且不正确地解释命令。 – 2012-07-31 09:08:34