You can do a list-comprehension:
test = ['path', 'name', 'user1', 'orig']
mylist = ['user' if 'user' in x else x for x in test]
# ['path', 'name', 'user', 'orig']
Answer from Austin on Stack OverflowI'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?
Python- how to replace characters in a list item in a list - Stack Overflow
How to Replace Characters in a List in Python? - Stack Overflow
python - How to replace a specific character in every element of a list - Stack Overflow
python - How to replace a character with another character in a list of string - Stack Overflow
You can do a list-comprehension:
test = ['path', 'name', 'user1', 'orig']
mylist = ['user' if 'user' in x else x for x in test]
# ['path', 'name', 'user', 'orig']
Note that when you do:
`mylist = 'user'`
You are replacing whatever there was in that list with 'user'. So instead you want to specify an index, say mylist[i] = 'user', or use append.
This however can be simplified using a list comprehension:
[i if 'user' not in i else 'user' for i in l ]
['path', 'name', 'user', 'orig']
The first problem is that replace doesn't change a string in-place, it just returns a new string. And you're ignoring that new string.
What you want is:
new_list = []
for x in list:
new_list.append(x.replace("[","").replace("]","").replace('"','').replace(" ","").replace(",","").replace("[",""))
You can simplify that with translate, or use a different way of filtering out the characters like a comprehension or a filter call. But the result will be the same.
The bigger problem is that what you're trying to do doesn't make any sense. None of the elements in your list have a [, ], ", etc. character in them. You're probably confusing the string representation of the list with the list itself.
If you want to join the members of a list, or to produce any representation of the list other than the default repr, just explicitly join them. For example, this gets what you seem to want:
''.join(list)
… and this gets a different representation:
' and '.join(list)
… and this gets roughly the same thing as repr:
'[' + ', '.join(map(repr, list)) + ']'
Use str.join:
>>> lis = ["/x01", "/x30", "/x30", "/x53", "/x46", "/x46", "/x46", "/x30", "/x30", "/x30", "/x31", "/x46", "/x46", "/x0D"]
>>> ''.join(lis)
'/x01/x30/x30/x53/x46/x46/x46/x30/x30/x30/x31/x46/x46/x0D'
Looking at your code, I think you were trying to apply str.replace on str version of the list. But that would be a weird way to do this, better use str.join:
>>> str(lis)
"['/x01', '/x30', '/x30', '/x53', '/x46', '/x46', '/x46', '/x30', '/x30', '/x30', '/x31', '/x46', '/x46', '/x0D']"
The above string is just a representation of the list object.
>>> str(lis).replace("[","").replace("]","").replace(" ","").replace(",","").replace("'","")
'/x01/x30/x30/x53/x46/x46/x46/x30/x30/x30/x31/x46/x46/x0D'
f = lambda x: x.replace("K", "000")
data = ["142", "1567", "153K", "32", "10", "50"]
print(list(map(f, data)))
In your code, 153K is not a valid literal for any type
I Interprete this list as string list.
Using replace function
[i.replace('K', '000') for i in list]
Then you can convert it to list o integer using int
[int(i.replace('K', '000')) for i in list]
In this case this list will return :
[142, 1567, 153000, 32, 10, 50]
As @Marcin says, Python strings are immutable. If you have a specific character/substring you want to replace, there is string.replace. You can also use lists of characters instead of strings, as described here if you want to support the functionality of changing one particular character.
If you want something like string.replace, but for an index rather than a substring, you can do something like:
def replaceOneCharInString(string, index, newString):
return string[:index] + newString + string[index+len(newString):]
You would need to do some length checking, though.
Edit: forgot string before the brackets on string[index+len(newString):]. Woops.
Since python strings are immutable, they cannot be modified. You need to make new ones. One way is as follows:
tmp_list = list(a_list[1])
tmp_list[10] = 'o' # simulates: list[1][10]='o'
new_str = ''.join(tmp_list)
#Gives |oooooooococooooooooi
# substitute the string in your list
a_list[1] = new_str
Strings are immutable. replace does not work in-place, it returns a new string. You need to reallocate that new string to the original name.
if x in z:
z = z.replace(x,"Firstname")
(Also, please use more than one space indentation.)
Consider your use of elif. If your first condition triggers, replacing the first name, will the last condition trigger to replace the last name? You may want to try two if else structures.
Consider the following:
z = 'abc'
if z[0] == 'a':
z = z.replace('a', '1')
elif z[1] == 'b':
z = z.replace('b', '2')
if z[2] == 'c':
z = z.replace('c', '3')
What will z be at the end of this block? Would removing the z = change that? How does changing the conditionals (if elif else) change the output?
Others have explained errors in posted code. An alternative using generator expression:
new = ''.join("*" if char in ['A','C','P'] else char for char in a)
print(new)
>>> '*GG*FTFG*DF*DTRF**GF*D*RTR*DF**DGFLKLI**'
You assign the result of a.replace(char, "*") to new, but then on the next iteration of the for loop, you again replace parts of a, not new. Instead of assigning to new, just assign the result to a, replacing the original string.
a = "AGGCFTFGADFADTRFCAGFADARTRADFACDGFLKLIAP"
rep = ['A','C','P']
for char in rep:
a = a.replace(char, "*")
print(a)
You have return secret half way through your function. This means that the remainder of the code in that function will not execute. You should move return secret to the end of the function definition.
You also are accepting a parameter to the create_table() function that you then immediately overwrite, you can get rid of this.
table is a mutable list, so just do:
table[row][col] = secret[i]
and remove the return secret or you won't get to the code.
A simple example:
import pprint
table = [['*', '*', '*', '*', '*'],
['*', '*', '*', '*', '*'],
['*', '*', '*', '*', '*'],
['*', '*', '*', '*', '*'],
['*', '*', '*', '*', '*']]
def create_table():
secret = 'ABCDEFGHIJKLMNOPQRSTUVWXY'
for row in range(5):
for col in range(5):
table[row][col] = secret[row*5 + col]
pprint.pprint(table)
create_table()
Output:
[['A', 'B', 'C', 'D', 'E'],
['F', 'G', 'H', 'I', 'J'],
['K', 'L', 'M', 'N', 'O'],
['P', 'Q', 'R', 'S', 'T'],
['U', 'V', 'W', 'X', 'Y']]