开发者

Python shlex.split(), ignore single quotes

开发者 https://www.devze.com 2023-03-23 13:33 出处:网络
How, in Python, can I use shlex.split() or similar to split strings, preserving only double quotes? Fo开发者_高级运维r example, if the input is \"hello, world\" is what \'i say\' then the output would

How, in Python, can I use shlex.split() or similar to split strings, preserving only double quotes? Fo开发者_高级运维r example, if the input is "hello, world" is what 'i say' then the output would be ["hello, world", "is", "what", "'i", "say'"].


import shlex

def newSplit(value):
    lex = shlex.shlex(value)
    lex.quotes = '"'
    lex.whitespace_split = True
    lex.commenters = ''
    return list(lex)

print newSplit('''This string has "some double quotes" and 'some single quotes'.''')


You can use shlex.quotes to control which characters will be considered string quotes. You'll need to modify shlex.wordchars as well, to keep the ' with the i and the say.

import shlex

input = '"hello, world" is what \'i say\''
lexer = shlex.shlex(input)
lexer.quotes = '"'
lexer.wordchars += '\''

output = list(lexer)
# ['"hello, world"', 'is', 'what', "'i", "say'"]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号