基于inpu的Python分区字符串

2024-06-26 10:00:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我想让Python将一个字符串划分为一个特定的字符。该字符(数学运算符;+, -, /, or x)将由用户通过输入定义。例如,如果用户输入"Cheese+Bacon",它应该给我["Cheese", "+", "Bacon"]。但是如果用户输入`“Cheese Bacon”,它将给我["Cheese", "-", "Bacon"],其他两个操作符也是如此。我有这个代码,但很明显,分区不能读取,因为它是一个列表。我怎么能这样做呢?你知道吗

operators = ['+', '-', '/', 'x']
for ops in operators:
    disGet.partition(operators)

disGet是对显示.get(),这是Tkinter中的一个输入小部件,播放器在其中输入。你知道吗


Tags: or字符串代码用户列表for定义运算符
3条回答

如果不想使用正则表达式,只需测试每个分区操作是否工作,并在其中一个操作工作时中断:

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

您可以检查一次字符串,然后查找每个操作,如果匹配,只需拉动拼接的字符串:

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?']

可以使用列表拼接。你知道吗

>>> s = "Cheese+Bacon"
>>> op = '+'
>>> x = [s.split(op)[0]] + [op] + [s.split(op)[-1]]
>>> x
['Cheese', '+', 'Bacon']

相关问题 更多 >