【问题标题】:Python split everything between ""sPython 在 "" 之间拆分所有内容
【发布时间】:2014-10-03 02:42:36
【问题描述】:

如何在 Python 中的 "" 之间分割所有内容?包括“”本身? 例如,我想将 print "HELLO" 之类的内容拆分为 ['print '],因为我拆分了引号中的所有内容,包括引号本身。

其他例子:

1) print "Hello", "World!" => ['print ', ', ']

2) if "one" == "one": print "one is one" => ['if ', ' == ', ': print ']

感谢任何帮助。

【问题讨论】:

  • 一种方法是'print "hello"'.split(chr(34)),其中 34 是双引号字符的 ASCII。
  • 你能再举一些例子来说明你所说的“分裂”是什么意思吗?最好是你已经尝试过的?
  • 我是否正确假设您想要获取未引用的字符串的每个部分?
  • @AnthonyForloney: chr() 如果这是他想要做的,那么技巧就没有必要了。 '"' 是一个非常好的拼写方式。
  • @Wooble 我刚刚注意到了,哦。我忘了引用引起错误的双引号(即split('"')),所以我选择了ASCII 方法。

标签: python split quotes


【解决方案1】:
>>> import re
>>> text = 'print "Hello"'
>>> re.sub(r'".*?"', r'', text)
'print '

帮助 OP 的单引号错误:

>>> import re
>>> text = 'print \'hello\''
>>> re.sub(r'\'.*?\'', r'', text)
'print '

【讨论】:

  • print 'hello',而不是print "Hello"
  • 只需用\' 注释掉' 符号。例如:text = 'print \'hello\''re.sub(r'\'.*?\'', r'', text)
【解决方案2】:

您可以将正则表达式'"[^"]*"' 用于re.split

例子:

txt='''\
print "HELLO"
print "Hello", "World!"
if "one" == "one": print "one is one"
'''

width=len(max(txt.splitlines(), key=len))

for line in txt.splitlines():
    print '{:{width}}=>{}'.format(line, re.split(r'"[^"]*"', line), width=width+1)

打印:

print "HELLO"                         =>['print ', '']
print "Hello", "World!"               =>['print ', ', ', '']
if "one" == "one": print "one is one" =>['if ', ' == ', ': print ', '']

【讨论】:

  • 方法相同,只是打印方式不同。只需说print line, re.split(r'"[^"]*"', line) 然后...
【解决方案3】:

使用re.split():

In [3]: re.split('".*?"', 'print "HELLO"')
Out[3]: ['print ', '']


In [4]: re.split('".*?"', '"Goodbye", "Farewell", and "Amen"')
Out[4]: ['', ', ', ', and ', '']

注意.*? 的使用,非贪婪的全消耗模式。

【讨论】:

  • 一个足够好的答案——至少它有点工作。
  • 在什么情况下不起作用?我很乐意改进答案。
  • 对不起,我迟到了 50 分钟。无论如何,当我用 print '...' 替换 print "..." 时——它不能同时解释 '' 和 "" 。但是不要把这个放在个人身上;所有答案都有这个错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-11
  • 2023-04-03
  • 2013-02-09
  • 1970-01-01
相关资源
最近更新 更多