I want to find something after a certain character. I am aware of how to find something before using rfind
, but not so sure of the syntax to find something after. Here is an example
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('.')])
Any ideas on how to use the syntax to find something after
print(text[text.rfind('.')+1:])
Two other methods you may try might include splitting the string, and also doing a regex substitution to isolate the substring you want:
text = 'Hello.world'
print(text.split('.')[1])
print(re.sub(r'^.*\.', '', text))
Splitting would proabably outperform re.sub
here, so I recommend split()
first.
print(text[text:.rfind('.')]) => print(text[text.find('.')+1:])
Here's another way to do it, str.partition and 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'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.