import shlex
str=shlex.shlex("ab,'cdsfd,sfsd',ewewq,5654",posix=True)
str.whitespace=','
str.whitesapce_split=True
b=list(str)
print b
['ab', 'cdsfd,sfsd', 'ewewq', '5654']
import shlex
str=shlex.shlex("ab,'cdsfd,sfsd',ewewq,5654")
str.whitespace=','
str.whitesapce_split=True
b=list(str)
print b
['ab', "'cdsfd,sfsd'", 'ewewq', '5654']
import shlex
lex = shlex.shlex('''This string has "some double quotes" and 'some single quotes'.''')
lex.quotes = '"'
lex.whitespace_split = True
b=list(lex)
['This', 'string', 'has', '"some double quotes"', 'and', "'some", 'single', "quotes'."]
在解析命令行参数的时候碰到python字符分割的问题,python中字符串分割默认都是在空格,但是我的参数中可能某个参数带有空格符,同时有双引号包围。
最近的python中引入了支持正则分割的shlex模块,他能很好的处理空格符的问题。如下
>>> import shlex
>>> shlex.split('this is "a test"')
['this', 'is', 'a test']
本文介绍如何利用Python的shlex模块处理包含特殊字符如空格和引号的字符串分割问题。通过示例展示了如何配置shlex实例来正确解析带有双引号和单引号的字符串。


被折叠的 条评论
为什么被折叠?



