从到ODO 9获取字符串

2024-04-19 07:16:34 发布

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

如何从示例字母“T”中的第一个字符到第一个斜杠“/”

TEST/0001需要测试

TEST2/0001需要获取TEST2

TEST3/0001需要获取TEST3


Tags: test示例字母字符test2斜杠test3
2条回答

在python中,可以使用split() function,它返回按指定字符拆分的元素数组。然后得到第一个元素:

yourString = "TEST/0001"

yourString.split("/")[0]

>>> 'TEST'

我会选择split解决方案,但是如果您正在寻找一个更完整同时简单的解决方案(假设您知道regex,不管怎样,它应该属于任何程序员的知识),那么您可以使用标准库re module中的一些快捷方法。在

使用相同数据的示例如下:

import re

lines = ["TEST/1000", "TEST2/1000", "TEST3/1000"]
pattern = "TEST\d*(?=/)"    # Take any string beginning with TEST, followed by 0 or more digits and a / character

for line in lines:
    match = re.match(pattern, line)

    if match is not None:
        print(match.group(0))    # match.group(0) returns the whole matched string, and not a part of it
    else:
        print("No match for %s" % line)

在我的设置中,在test.py文件中运行此脚本会产生:

^{pr2}$

相关问题 更多 >