How to remove the left part of a string?
in stackoverflow ∙
2 mins read
∙ Tags: Python, String
How to remove the left part of a string?
Question by grigoryvp
I have some simple python code that searches files for a string e.g. path=c:\path
, where the c:\path
part may vary. The current code is:
def find_path(i_file):
lines = open(i_file).readlines()
for line in lines:
if line.startswith("Path="):
return # what to do here in order to get line content after "Path=" ?
What is a simple way to get the text after Path=
?
Answer by Milovan Tomašević
removeprefix()
and removesuffix()
string methods added in Python 3.9 due to issues associated with lstrip
and rstrip
interpretation of parameters passed to them. Read PEP 616 for more details.
# in python 3.9
>>> s = 'python_390a6'
# apply removeprefix()
>>> s.removeprefix('python_')
'390a6'
# apply removesuffix()
>>> s = 'python.exe'
>>> s.removesuffix('.exe')
'python'
# in python 3.8 or before
>>> s = 'python_390a6'
>>> s.lstrip('python_')
'390a6'
>>> s = 'python.exe'
>>> s.rstrip('.exe')
'python'
removesuffix
example with a list:
plurals = ['cars', 'phones', 'stars', 'books']
suffix = 's'
for plural in plurals:
print(plural.removesuffix(suffix))
output:
car
phone
star
book
removeprefix
example with a list:
places = ['New York', 'New Zealand', 'New Delhi', 'New Now']
shortened = [place.removeprefix('New ') for place in places]
print(shortened)
output:
['York', 'Zealand', 'Delhi', 'Now']
Improve this page:
Share on:
Keep going!
Keep going ×2!
Give me more!
Thank you, thank you
Far too kind!
Never gonna give me up?
Never gonna let me down?
Turn around and desert me!
You're an addict!
Son of a clapper!
No way
Go back to work!
This is getting out of hand
Unbelievable
PREPOSTEROUS
I N S A N I T Y
FEED ME A STRAY CAT
Share on:
Comments 💬
Templates (for web app):
Loading…
Permalink