我希望Python分区一个字符串直到某个字符。该字符(数学运算符; +, -, /, or x
)将由用户通过输入定义。例如,如果用户输入"Cheese+Bacon"
,则应该向我["Cheese", "+", "Bacon"]
。但是如果用户输入“" Cheese-Bacon"”,它会给我["Cheese", "-", "Bacon"]
,其他两个运营商也是如此。我有这个代码,但显然.partition无法读取,因为它是一个列表。我怎么能这样做?
operators = ['+', '-', '/', 'x']
for ops in operators:
disGet.partition(operators)
disGet是对display.get()的引用,它是Tkinter中的Entry小部件,是播放器输入的位置。
答案 0 :(得分:1)
如果您不想使用正则表达式路由,只需测试以查看每个分区操作是否有效,并在其中一个分区操作时中断:
disGet = "cheese-bacon"
operators = '+-/x'
for op in operators:
part = disGet.partition(op)
if part[1]: # contains the partitioning string on success, empty on failure
break
else: # nothing worked, so do whatevs
part = None
答案 1 :(得分:0)
可以使用列表拼接。
>>> s = "Cheese+Bacon"
>>> op = '+'
>>> x = [s.split(op)[0]] + [op] + [s.split(op)[-1]]
>>> x
['Cheese', '+', 'Bacon']
答案 2 :(得分:0)
您可以检查一次字符串并为每个操作执行查找,如果匹配则只需拉动字符串拼接:
operators = {'+', '-', '/', 'x'}
s = "Cheese-Bacon"
out = next(([s[:i], ch, s[i+1:]] for i, ch in enumerate(s) if ch in operators), None)
if out:
# do whatever
如果您想获得多个运营商:
def split_keep_sep(s, ops):
inds = ((i, ch) for i, ch in enumerate(s) if ch in ops)
prev = 0
for i, ch in inds:
yield s[prev:i]
yield ch
prev = i + 1
yield s[i+1:]
演示:
In [26]: operators = {'+', '-', '/', 'x'}
In [27]: s = "cheese+bacon-patty/lettuce?"
In [28]: print(list(split_keep_sep(s, operators)))
['cheese', '+', 'bacon', '-', 'patty', '/', 'lettuce?']