从末尾剪切一个子字符串,直到某个字符第一次出现

Cut a substring from the end until the first occurrence of a certain character

我有一个字符串,可以这样说:
abc$defg..hij/klmn

在遇到 $ 符号之前,如何获取从最后一个字符剪切掉的子字符串。注意 $ 可能是一个特殊字符,字符串中可能还有其他特殊字符。

输出应该是:
defg..hij/klmn

我正在使用 python 2.7 及更高版本。

您需要先获取第一个字符的出现,然后从 index 加上 1:

testStr = "abc$defg..hij/klmn"
try:
    index = testStr.index()
    start = index + 1
    print(str[start:])
except:
    print("Not in string")

注意:这会return一个字符串从第一个&之后到最后。如果你想在 $ 中包含多个字符串,接受的答案很有效。

您可以使用 split 函数:

your_string = "abc$defg..hij/klmn"
split_char = "$"

substring = your_string.split(split_char)[-1]

这是另一种方法。它从末尾检查每个字符,直到遇到特殊字符。

text = "abc$defg..hij/klmn"
newstring = text[::-1]

output = ""

for character in newstring:
    if character != "$":
        output += character
    else:
        break

print(output[::-1])