How do I remove a substring from the end of a string?
strip
doesn't mean "remove this substring". x.strip(y)
treats y
as a set of characters and strips any characters in that set from both ends of x
.
On Python 3.9 and newer you can use the removeprefix
and removesuffix
methods to remove an entire substring from either side of the string:
url = 'abcdc.com'
url.removesuffix('.com') # Returns 'abcdc'
url.removeprefix('abcdc.') # Returns 'com'
The relevant Python Enhancement Proposal is PEP-616.
On Python 3.8 and older you can use endswith
and slicing:
url = 'abcdc.com'
if url.endswith('.com'):
url = url[:-4]
Or a regular expression:
import re
url = 'abcdc.com'
url = re.sub('\.com$', '', url)
Replace all text between 2 strings python
You need Regular Expression
:
>>> import re
>>> re.sub('\nThis.*?ok','',a, flags=re.DOTALL)
' Example String'
Replace a string located between
import re
Variable = "The sun shines, that's fine [not, for, everyone] and if it rains, it Will Be better."
Variable1 = re.sub("\[[^]]*\]", lambda x:x.group(0).replace(',',''), Variable)
First you need to find the parts of the string that need to be rewritten (you do this with re.sub
). Then you rewrite that parts.
The function var1 = re.sub("re", fun, var)
means: find all substrings in te variable var
that conform to "re"
; process them with the function fun
; return the result; the result will be saved to the var1
variable.
The regular expression "[[^]]*]" means: find substrings that start with [
(\[
in re), contain everything except ]
([^]]*
in re) and end with ]
(\]
in re).
For every found occurrence run a function that convert this occurrence to something new.
The function is:
lambda x: group(0).replace(',', '')
That means: take the string that found (group(0)
), replace ','
with ''
(remove ,
in other words) and return the result.
Remove string between 2 characters from text string
In [11]: re.sub(r'\[.*?\]', '', 'abcd[e]yth[ac]ytwec')
Out[11]: 'abcdythytwec'
How to create a function in Python3 to return a substring from a string between two markers using regular expression?
import re
def findText(marker1, marker2, text):
search_for = r".+" + marker1 + r"(.+?)" + marker2 + ".+"
m = re.search(search_for, text)
if m:
found = m.group(1)
print(found) #print what was found
return(found)
findText("AAA", "BBB", "thisisAAAtestTextOnlyBBBxyz")
result:testTextOnly
Related Topics
Check If Values of Multiple Columns Are the Same (Python)
Python: How to Match Nested Parentheses With Regex
Accuracy Score Valueerror: Can't Handle Mix of Binary and Continuous Target
How to Merge Elements in List in Python With Condition
Compare a Column Between 2 CSV Files and Write Differences Using Python
Grab a Number After a String in a File
Splitting Timestamp Column into Separate Date and Time Columns
How to Cleanly Uninstall Ansible
How to Change the Title Bar in Tkinter
Python Json Add Key-Value Pair
Python Overflowerror: Int Too Large to Convert to Float
Remove Very First Row in Pandas
How to Use Anaconda Python to Execute a .Py File
How to Dynamically Build a Json Object
How to Write Multiple Images (Subplots) into One Image
Pyspark Replace All Values in Dataframe With Another Values
Cv2.Videocapture.Open() Always Returns False
How to Append Data Using Openpyxl Python to Excel File from a Specified Row