You need to re-assign to li each time, kind of recursive replacement. Because for now you always go from original li to t with a different replacement letter
li = 'Text 1. Text 2? Text 3!'
i = ['.', '?', '!']
for y in i:
li = li.replace(y, '')
You can also use regex module re and pattern [.?!]
li = 'Text 1. Text 2? Text 3!'
i = ['.', '?', '!']
li = re.sub("[" + "".join(i) + "]", '', li)
Answer from azro on Stack Overflowpython - Finding and replacing elements in a list - Stack Overflow
string - Is there a method like .replace() for list in python? - Stack Overflow
Change values in a list using a for loop (python) - Stack Overflow
Curious about logic behind replacing elements of a list.
Videos
You need to re-assign to li each time, kind of recursive replacement. Because for now you always go from original li to t with a different replacement letter
li = 'Text 1. Text 2? Text 3!'
i = ['.', '?', '!']
for y in i:
li = li.replace(y, '')
You can also use regex module re and pattern [.?!]
li = 'Text 1. Text 2? Text 3!'
i = ['.', '?', '!']
li = re.sub("[" + "".join(i) + "]", '', li)
You have to update the value of li everytime replace method is used
li = 'Text 1. Text 2? Text 3!'
i = ['.', '?', '!']
for y in i:
li = li.replace(y, '')
print(li)
this way the loop checks for the first string to replace then re-assigns the new li value to li and then checks for next string to replace.
Try using a list comprehension and a conditional expression.
>>> a=[1,2,3,1,3,2,1,1]
>>> [4 if x==1 else x for x in a]
[4, 2, 3, 4, 3, 2, 4, 4]
You can use the built-in enumerate to get both index and value while iterating the list. Then, use the value to test for a condition and the index to replace that value in the original list:
>>> a = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1]
>>> for i, n in enumerate(a):
... if n == 1:
... a[i] = 10
...
>>> a
[10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10]
Thereโs nothing built-in, but itโs just a loop to do the replacement in-place:
for i, word in enumerate(words):
if word == 'chicken':
words[i] = 'broccoli'
or a shorter option if thereโs always exactly one instance:
words[words.index('chicken')] = 'broccoli'
or a list comprehension to create a new list:
new_words = ['broccoli' if word == 'chicken' else word for word in words]
any of which can be wrapped up in a function:
def replaced(sequence, old, new):
return (new if x == old else x for x in sequence)
new_words = list(replaced(words, 'chicken', 'broccoli'))
No such method exists, but a list comprehension can be adapted to the purpose easily, no new methods on list needed:
words = 'I like chicken'.split()
replaced = ['turkey' if wd == "chicken" else wd for wd in words]
print(replaced)
Which outputs: ['I', 'like', 'turkey']
For each iteration of the for loop the variable i is assigned with just a copy of the value of an item in vallist, so changes made to i won't be reflected in i.
You should update the items of i via index, which you can generate with the enumerate function:
for index, value in enumerate(vallist):
if value >= 10:
vallist[index] = letters[value]
rd1, rd2, gd1, gd2, bd1, bd2 = 10, 11, 12, 13, 14, 9
letters = {
10 : "A",
11 : "B",
12 : "C",
13 : "D",
14 : "E",
15 : "F"
}
vallist = [rd1, rd2, gd1, gd2, bd1, bd2]
for index, value in enumerate(vallist):
if value >= 10 and value <= 15:
vallist[index] = letters[value]
print(vallist)
As mentioned in the other comment you need both the index and the value while looping over your vallist. so you can replace the value on the index with the value in your dictionary.
Let's say we have a list x = ["a","b","c","b"] in which I want to replace an element, or all elements of a specific value, let's say "b". The way to do it would be (putting aside some fancy methods and such):
x = ["a","b","c","b"]
for n in x:
if n == "b":
i = x.index(n)
x[i] = "W"which is fine. But I was wondering why do we need specify index of the n variable since python -in this case- already knows it. Why can't we do something like that:
x = ["a","b","c","b"]
for n in x:
if n == "b":
n = "W"
print(x)
The list will not be changed. Why not? Python knows which n we want to change, that's what the if statement is here for. So why do we need extra step of specifying the position of an object with its index? Is it something inherited from C language?
There is a lot of duplication in your code. I would suggest:
import random
word = list('GTGATCCAGT')
BASES = "ACGT"
for index, base in enumerate(word[:5]):
word[index] = random.choice(BASES.replace(base, ""))
word = "".join(word)
A trial run gives me:
>>> word
'TACTACCAGT'
Note the switch to a list - strings in Python are immutable, so you can't (easily) change an individual character. By contrast, lists are mutable, so you can switch the item at a given index without any fuss.
Your loop doesn't currently have enough information to do what you want: in particular, it doesn't know which base you are currently looking at, only what its value is. You could use the builtin enumerate to introduce that information, but a simpler way would be to change the logic so it doesn't rebuild the string each time - instead, write a generator that gives you each successive new_base, and join them all into new_word at the end. It looks like this:
def rebase(word):
for base in word:
print base
if base == 'A':
new_base = random.choice('CTG')
print new_base
yield new_base
# etc
else:
# If you didn't change this base, yield the original one
yield base
new_word = word[:5] + ''.join(rebase(word[5:]))
You might also want to use a dictionary to avoid the chain of ifs - like this:
def rebase(word):
possible_replacements = {'A': 'CTG', 'C': 'ATG'} # etc
for base in word:
print base
try:
yield random.choice(possible_replacements[base])
except KeyError:
# If you didn't change this base, yield the original one
yield base
new_word = word[:5] + ''.join(rebase(word[5:]))
Your problem comes from the fact that you keep on defining the function every loop iteration, but you don't run it or save its output. The minimum changes to get this to work are:
def replaceMultiple(s, unwanted, input_char):
# Iterate over the strings to be replaced
for elem in unwanted:
# Replace the string, does not do anything if `elem` not in `s`
s = s.replace(elem, input_char)
return s
flat_data2_new = [replaceMultiple(x) for x in flat_data2]
You can try:
input_char = ""
conv = ''.maketrans({c: input_char for c in unwanted})
l = list() # if you want a list of all your strings
for i in range(len(flat_data2)):
mainString = flat_data2[i].translate(conv)
l.append(mainString)
Your not assigning the return value of replace() to anything. Also, readlines and str(i) are unnecessary.
Try this:
filename = "/Users/sacredgeometry/Desktop/data.txt"
text = open(filename, 'r')
linesNew = []
for line in text:
# i is already a string, no need to str it
# temp = str(i)
# also, just append the result of the replace to linesNew:
linesNew.append(line.replace(' ', ', ', 2))
# DEBUGGING THE CODE
print(linesNew[0])
print(linesNew[1])
# Another test to check that the replace works ... It does!
test2 = linesNew[0].replace(' ', ', ',2)
test2 = test2.replace('\t', ', ')
print('Proof of Concept: ' + '\n' + test2)
text.close()
Strings are immutable. replace returns a new string, which is what you have to insert into the linesNew list.
# This bloody for loop is the problem
for i in lines:
temp = str(i)
temp2 = temp.replace(' ', ', ',2)
linesNew.append(temp2)