我在需要删除字符串的第一个不确定部分的地方有输入.

可能的输入:

/a (some optional text)
/a@w (some optional text)
/an (some optional text)
/an@w (some optional text)
/am (some optional text)
/am@w (some optional text)

/b (some optional text)
/b@w (some optional text)
/bn (some optional text)
/bn@w (some optional text)
/bm (some optional text)
/bm@w(some optional text)

c...

我只需要输出‘’或(一些可选文本),如果存在

推荐答案

regex

import re

def remove_indefinite_part(input_string):
    # Define the regular expression pattern to match the first indefinite part
    pattern = r'^\/[a-zA-Z]+(@[a-zA-Z]+)?\s?'

    # Find the first match using the pattern
    match = re.search(pattern, input_string)

    if match:
        # Remove the matched part from the input string
        modified_string = input_string[len(match.group()):].strip()
    else:
        modified_string = input_string

    return modified_string

# Test the function with example inputs
inputs = [
    '/a (some optional text)',
    '/a@w (some optional text)',
    '/an (some optional text)',
    '/an@w (some optional text)',
    '/am (some optional text)',
    '/am@w (some optional text)',
    '/b (some optional text)',
    '/b@w (some optional text)',
    '/bn (some optional text)',
    '/bn@w (some optional text)',
    '/bm (some optional text)',
    '/bm@w (some optional text)'
]

for input_str in inputs:
    result = remove_indefinite_part(input_str)
    print(result)

输出:

(some optional text)
(some optional text)
(some optional text)
(some optional text)
(some optional text)
(some optional text)
(some optional text)
(some optional text)
(some optional text)
(some optional text)
(some optional text)
(some optional text)

Python相关问答推荐

手动为pandas中的列上色

根据多列和一些条件创建新列

如何在telegram 机器人中发送音频?

将从Python接收的原始字节图像数据转换为C++ Qt QIcon以显示在QStandardProject中

code _tkinter. Tcl错误:窗口路径名称错误.!按钮4"

使文本输入中的文本与标签中的文本相同

在matplotlib动画gif中更改配色方案

2维数组9x9,不使用numpy.数组(MutableSequence的子类)

韦尔福德方差与Numpy方差不同

max_of_three使用First_select、second_select、

Python json.转储包含一些UTF-8字符的二元组,要么失败,要么转换它们.我希望编码字符按原样保留

删除最后一个pip安装的包

用NumPy优化a[i] = a[i-1]*b[i] + c[i]的迭代计算

Pandas—合并数据帧,在公共列上保留非空值,在另一列上保留平均值

如何使用表达式将字符串解压缩到Polars DataFrame中的多个列中?

海上重叠直方图

当递归函数的返回值未绑定到变量时,非局部变量不更新:

如何指定列数据类型

在输入行运行时停止代码

具有相同图例 colored颜色 和标签的堆叠子图