Python3: Remove a Substring Between Two Delimiting Char

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



Leave a reply



Submit