Reputation: 925
I am trying to figure out a way to create a single expression that will work for both branch1 and branch2 below?I need to remove the words -dev and -rel from branch,how can I do that?
chars_to_remove = ['-dev','-rel']
branch1 = 'bt.lnx.2.1-dev'
branch2 = 'bt.lnx.2.1-rel'
component = branch1.translate(None, ''.join(chars_to_remove))//should work for both branch1 & branch2
print component
EXPECTED OUTPUT:(for both branch1 and branch2)-
bt.lnx.2.1
Upvotes: 0
Views: 398
Reputation: 11134
import re
chars_to_remove = ['({}.*)'.format(i) for i in chars_to_remove]
def trimmer(your_string):
return re.sub(r'|'.join(chars_to_remove),'',your_string)
print trimmer(branch1)
print trimmer(branch2)
Output:
'bt.lnx.2.1'
'bt.lnx.2.1'
Upvotes: 0
Reputation: 3555
use regex
, it remove chars_to_remove
at end of string, remove the $
from the regex if you wanna remove all the match including match at middle also
import re
chars_to_remove = ['-dev','-rel'] # modify char to remove here
def remove_char(s):
return re.sub("({})$".format('|'.join(chars_to_remove)), '', s)
branch1 = 'bt.lnx.2.1-dev'
branch2 = 'bt.lnx.2.1-rel'
remove_char(branch1) # 'bt.lnx.2.1'
remove_char(branch2) # 'bt.lnx.2.1'
Upvotes: 0
Reputation: 55
Try this:
print (branch1.replace('-dev','').replace('-rel',''))
print (branch2.replace('-dev','').replace('-rel',''))
Upvotes: 3
Reputation: 51
If they're always at the end you can simply use string slicing.
if branch[-4:] == '-dev' or branch[-4:] == '-rel':
branch = branch[:-4]
If they're not all at the end, you might want to use the re module.
Upvotes: -1