Reputation: 197
I wanted to remove word in a sentence if word starts or contains certain chars.
Ex:
string_s = '( active parts ) acetylene cas89343-06-6'
if word contains or starts with cas remove entire word from string
input1 = '( active parts ) acetylene cas89343-06-6'
output1 = '( active parts ) acetylene'
input2 = '( active parts ) acetylene th.cas1345'
output2 = '( active parts ) acetylene'
Upvotes: 0
Views: 65
Reputation: 5788
One liner:
' '.join([*filter(lambda x: "cas" not in x, input1.split())])
Upvotes: 0
Reputation: 521239
Use re.sub
with the pattern \b[\w-]*cas[\w-]*\b
, and replace with a single space, then trim the output:
string_s = '( active parts ) acetylene cas89343-06-6'
output = re.sub(r'\b[\w-]*cas[\w-]*\b', ' ', string_s).strip()
print(string_s + '\n' + output)
This prints:
( active parts ) acetylene cas89343-06-6
( active parts ) acetylene
Upvotes: 1
Reputation: 174
you can do this by:-
string = "hello how are you"
character = "a"
newString = []
for i in string.split(' '):
if not character in i:
newstring.append(i)
newString = ' '.join(newString)
Upvotes: 0