这是解释这个问题的最简单方法.这是我正在使用的:
re.split('\W', 'foo/bar spam\neggs')
-> ['foo', 'bar', 'spam', 'eggs']
Run Code Online (Sandbox Code Playgroud)
这就是我想要的:
someMethod('\W', 'foo/bar spam\neggs')
-> ['foo', '/', 'bar', ' ', 'spam', '\n', 'eggs']
Run Code Online (Sandbox Code Playgroud)
原因是我想将一个字符串拆分成标记,操纵它,然后再将它重新组合在一起.
我正在尝试拆分包含 python 函数的字符串,以便生成的输出将单独的函数保留为列表元素。
s='hello()there()'应该拆分为['hello()', 'there()']
为此,我使用正则表达式先行在右括号上拆分,但不在字符串末尾拆分。
虽然前瞻似乎有效,但我无法)按照各种帖子中的建议将结果保留在结果字符串中。简单地用正则表达式分割会丢弃分隔符:
import re
s='hello()there()'
t=re.split("\)(?!$)", s)
Run Code Online (Sandbox Code Playgroud)
这导致:'hello(', 'there()']。
s='hello()there()'
t=re.split("(\))(?!$)", s)
Run Code Online (Sandbox Code Playgroud)
将分隔符包装为一个组会导致)保留为一个单独的元素:与使用该函数的方法['hello(', ')', 'there()']
一样:filter()
s='hello()there()'
u = list(filter(None, re.split("(\))(?!$)", s)))
Run Code Online (Sandbox Code Playgroud)
再次导致括号作为单独的元素:['hello(', ')', 'there()']
如何拆分这样的字符串以使函数在输出中保持完整?
我目前正在研究一个Python项目,我想知道如何使用空格分隔符拆分字符串.例如,
"I'm a test"会的["I'm", "", "a", "", "test"].所以,如果有人知道该怎么做,请帮助我.
祝你有美好的一天 !