【问题标题】:How to get a string after and before a specific substring in Python? [duplicate]如何在Python中的特定子字符串之后和之前获取字符串? [复制]
【发布时间】:2020-11-18 19:55:09
【问题描述】:

如何在特定子字符串之后和之前获取字符串?

比如我想获取:中前后的字符串

my_string="str1:str2"

(在这种情况下是:str1str2)。

【问题讨论】:

  • my_string.split(':')

标签: python string substring


【解决方案1】:

根据您的用例,您可能需要不同的东西,但这可能最适合您:

lst = my_string.split(":")

那么,lst 将是:['str1', 'str2']

您还可以通过以下方式找到子字符串的索引:

substring = ":"
index = my_string.find(":")

然后在该索引上拆分字符串:

first_string = my_string[:index]
second_string = my_string[index+len(substring):]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    相关资源
    最近更新 更多