簡體   English   中英

在某個字符之后查找文本

[英]Finding text after a certain character

我想在某個字符之后找到一些東西。 我知道如何在使用rfind之前找到一些東西,但不太確定之后找到東西的語法。 這是一個例子

text = 'Hello.world' 

#to find something before
print(text[:text.rfind('.')])
# out : 
Hello

# to find something after, I tried this, but of course it's incorrect
print(text[text:.rfind('.')])

關於如何使用語法查找內容的任何想法

print(text[text.rfind('.')+1:])

您可以嘗試的其他兩種方法可能包括拆分字符串,以及進行正則表達式替換以隔離您想要的 substring:

text = 'Hello.world'
print(text.split('.')[1])

print(re.sub(r'^.*\.', '', text))

在這里拆分可能會勝過re.sub ,所以我建議先split()

print(text[text:.rfind('.')]) => print(text[text.find('.')+1:])

這是另一種方法,str.partition 和 str.rpartition

def find(text, sep=' ', right=False):
    if not (text and sep) or sep not in text:
        return None
    return text.rpartition(sep)[2] if right else text.partition(sep)[0]

find('Hello.Word', '.')         # 'Hello'
find('Hello.Word', '.', True)   # 'Word'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM