Home > Mobile >  Match string "words" with an array
Match string "words" with an array

Time:10-04

I am using this method to match a string with an array. However, I want to match entire words, instead of each character in a string.

string = "Take a pill when you are ill"
array = ['bill', 'chill', 'pill']
if any(x in string for x in array):
    string = string.replace('ill', 'sick')    
print(string)

I want this block of code to return:

Take a pill when you are sick

But it returns:

Take a psick when you are sick

How do I do this?

CodePudding user response:

Change this line to also match empty spaces:

if any(x in string for x in array):
    string = string.replace(' ill ', ' sick ')  

CodePudding user response:

You can change the line

`if any(x in string for x in array):
string = string.replace('ill', 'sick')`

To

`if any(x in string for x in array):
string = string.replace(' ill', 'sick')`

Now it will only replace sick with ill

CodePudding user response:

You need to do it this way,

string = "Take a pill when you are ill"
array = ['bill', 'chill', 'pill']
if any(x in string for x in array):
    string = string.replace(' ill', ' sick')    
print(string)

CodePudding user response:

this code will check any 'ill' in the string and change it with 'sick'. What you can do is

string = string.replace('ill', 'sick')

replace this with string = string.replace(' ill', ' sick') this.

CodePudding user response:

You can use regex to only replace when a word appears on its own. \b matches word boundaries: it doesn't consume any characters but will only match at the boundary between word characters ([A-Za-z0-9_]) and non-word characters.

import re

string = "Take a pill when you are ill"
array = ['bill', 'chill', 'pill']
if any(x in string for x in array):
    string = re.sub(r'\bill\b', 'sick', string)

print(string)
  • Related