You can use a list comprehension with an if-else.
list_A = ['hello', 'world', 'goodbye', 'world']
list_B = [word if word != 'world' else 'friend' for word in list_A]
You now have a new list, list_B, where all instances of the word "world" have been replaced with "friend".
pandas - How to replace words in list with Python - Stack Overflow
How Do I Replace Words In a String With Items In a List In Python - Stack Overflow
How to replace a word found in a string with what is in the list in Python - Stack Overflow
text - Replace all words from word list with another string in python - Stack Overflow
You can use a list comprehension with an if-else.
list_A = ['hello', 'world', 'goodbye', 'world']
list_B = [word if word != 'world' else 'friend' for word in list_A]
You now have a new list, list_B, where all instances of the word "world" have been replaced with "friend".
If you have unique values in your list:
my_list[my_list.index('old_word')]='new_word'
Iterate over the invalid_list and use the in-built replace() function to replace the substring.
for i in invalid_list:
s = [string.replace(i, 'xyz') for string in s]
Looping over the items of invalid_list is inefficient. This increases the complexity of the algorithm.
An efficient solution would be to use a regex to search motifs in each string only once:
s = ['123xyz', '456xye','789xyf']
invalid_list = ['xye','xyf']
import re
regex = re.compile('|'.join(map(re.escape, invalid_list)))
s2 = [regex.sub('xyz', x) for x in s]
Output:
['123xyz', '456xyz', '789xyz']
avoid matching partial words:
s = ['123xyz', '456xye','789xyf']
invalid_list = ['xy','xye','xyf']
import re
regex = re.compile(f"({'|'.join(map(re.escape, invalid_list))})\b")
s2 = [regex.sub('xyz', x) for x in s]
# ['123xyz', '456xye', '789xyf']
They advise using the re library here, however, I think it's easier, easier and better to use simple text.format() formatting
Code example:
list_of_words = ['text', 'be', 'there']
text = "This is an example {}. Normally there would {} something important here but {} isn't.".format(*list_of_words)
The output will look like this:
This is an example text. Normally there would be something important here but there isn't.
Try re.sub with custom function:
import re
lst = ["text", "be", "there"]
text = "This is an example [word]. Normally there would [word] something important here but [word] isn't."
text = re.sub(r"\[word\]", lambda _, i=iter(lst): next(i), text)
print(text)
Prints:
This is an example text. Normally there would be something important here but there isn't.
You can do that with a single call to sub:
big_regex = re.compile('|'.join(map(re.escape, prohibitedWords)))
the_message = big_regex.sub("repl-string", str(word[1]))
Example:
>>> import re
>>> prohibitedWords = ['Some', 'Random', 'Words']
>>> big_regex = re.compile('|'.join(map(re.escape, prohibitedWords)))
>>> the_message = big_regex.sub("<replaced>", 'this message contains Some really Random Words')
>>> the_message
'this message contains <replaced> really <replaced> <replaced>'
Note that using str.replace may lead to subtle bugs:
>>> words = ['random', 'words']
>>> text = 'a sample message with random words'
>>> for word in words:
... text = text.replace(word, 'swords')
...
>>> text
'a sample message with sswords swords'
while using re.sub gives the correct result:
>>> big_regex = re.compile('|'.join(map(re.escape, words)))
>>> big_regex.sub("swords", 'a sample message with random words')
'a sample message with swords swords'
As thg435 points out, if you want to replace words and not every substring you can add the word boundaries to the regex:
big_regex = re.compile(r'\b%s\b' % r'\b|\b'.join(map(re.escape, words)))
this would replace 'random' in 'random words' but not in 'pseudorandom words'.
try this:
prohibitedWords = ["MVGame","Kappa","DatSheffy","DansGame","BrainSlug","SwiftRage","Kreygasm","ArsonNoSexy","GingerPower","Poooound","TooSpicy"]
themessage = str(word[1])
for word in prohibitedwords:
themessage = themessage.replace(word, "(I'm an idiot)")
print themessage
It's really hard to identify what you want, but if you are trying to print alumni data living in Madrid, try below.
students = [
('Marcos', 23, 'Madrid', 850, '2388711341'),
('Elena', 35, 'MaDrid', 360, '0387700342'),
('Carmen', 21, 'Getafe', 50, '0014871388'),
('Carlos', 41, 'MAdrid', 580, '00887118456'),
('Maria', 28, 'Madrixx', 150, '587')
]
for student_detail in students:
if student_detail[2].lower().startswith('madri'):
print(f"The user {student_detail[0]}, lives in Madrid. S/He is {student_detail[1]} years old and has {student_detail[3]} as debt")
To filter your output you can f.e. use a simple if condition on a all-lowercase 'madrid':
students = [
('Marcos', 23, 'Madrid', 850, '2388711341'),
('Elena', 35, 'MaDrid', 360, '0387700342'),
('Carmen', 21, 'Getafe', 50, '0014871388'),
('Carlos', 41, 'MAdrid', 580, '00887118456'),
('Maria', 28, 'Madrixx', 150, '587')
]
for item in students:
# decompose the item into its parts - this also fixes your NameError
student, age, town, debt, something = item
# use the decomposed variables instead of item[.]
# make town all lowercase and compare - only print if matches
if town.lower() == "madrid":
print(f'The user {student} lives in {town.title()}, has an age of '
f'{age} and its debt is: {debt} EUR.')
Output:
# if you simply print town
The user Marcos lives in Madrid, has an age of 23 and its debt is: 850 EUR.
The user Elena lives in MaDrid, has an age of 35 and its debt is: 360 EUR.
The user Carlos lives in MAdrid, has an age of 41 and its debt is: 580 EUR.
# with town.title()
The user Marcos lives in Madrid, has an age of 23 and its debt is: 850 EUR.
The user Elena lives in Madrid, has an age of 35 and its debt is: 360 EUR.
The user Carlos lives in Madrid, has an age of 41 and its debt is: 580 EUR.
@marmeladze pointed out I missed Maria, who seems to be incapable of using her correct town-name - you can mitigate her inabilities by using:
if "madrid".startswith(town.lower()[:4]):
instead of
if town.lower() == "madrid":
to get an output of:
The user Marcos lives in Madrid, has an age of 23 and its debt is: 850 EUR.
The user Elena lives in Madrid, has an age of 35 and its debt is: 360 EUR.
The user Carlos lives in Madrid, has an age of 41 and its debt is: 580 EUR.
The user Maria lives in Madrixx, has an age of 28 and its debt is: 150 EUR.
I just hope you never get anybody from 'Madravingpeopletown' into your list - they would show up as well...
Use a set for unique_words. Sets are considerably faster than lists for determining if an item is in them (see Python Sets vs Lists ).
Also, it's only a stylistic issue but I think you should drop the brackets in the if. It looks cleaner.
The code you have posted doesn't actually do any replacement. Here is a snippet that does:
for key,word in enumerate(data):
if word in unique_words:
data[key] = replacement
Here's a more compact way:
new_list = [replacement if word in unique_words else word for word in big_list]
I think unique_words is an odd name for the variable considering its use, perhaps it should be search_list?
Edit:
After your comment, perhaps this is better:
from collections import Counter
c = Counter(data)
only_once = [k for k,v in c.iteritems() if v == 1]
# Now replace all occurances of these words with something else
for k, v in enumerate(data):
if v in only_once:
data[k] = replacement
I'm trying to replace the same characters in a list of strings but nothing is happening?
list = ["stacy", "tracy", "kacy"]
newlist=[]
for x in list:
x.replace("cy","fi")
newlist.append(x)
print(newlist)What's wrong here?