python - How to replace a character within a string in a list? - Stack Overflow
A list of string replacements in Python - Stack Overflow
Making str.replace() accept lists - Ideas - Discussions on Python.org
python - Replace in strings of list - Stack Overflow
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?
Looks like a good opportunity to use a loop:
mapping = { 'A':'1', 'B':'2', 'C':'3', 'D':'4', 'E':'5'}
for k, v in mapping.iteritems():
my_string = my_string.replace(k, v)
A faster approach if you don't mind the parentheses would be:
mapping = [ ('A', '1'), ('B', '2'), ('C', '3'), ('D', '4'), ('E', '5') ]
for k, v in mapping:
my_string = my_string.replace(k, v)
You can easily use string.maketrans() to create the mapping string to pass to str.translate():
import string
trans = string.maketrans("ABCDE","12345")
my_string = my_string.translate(trans)
>>> a = ["abcd:+;", "(l&'kka)"]
>>> a = [re.sub('[\(\)&\':+]', '', x) for x in a]
>>> a
['abcd;', 'lkka']
>>>
for index,x in enumerate(a):
a[index] = re.sub('[\(\)&\':+]', '', x)
Your changing the value but not updating your list. enumerate is function that return tuple (index,value) for each item of list
Your error seems to indicate that your string_list is not a list of string but a real string (that doesn't support assignement because a string is immutable).
If your string_list was a real list of strings, like this for example : string_list = ["first", "second", "", "fourth"], then you will be able to do string_list[2] = "third" to obtain string_list = ["first", "second", "third", "fourth"].
If you need to automatically detect where an empty string is located in your list, try with index :
string_list[string_list.index("")] = "replacement string"
print string_list
>>> ["first", "second", "replacement string", "fourth"]
You say you have a list of strings but from you error it looks like you're trying to index a string
l = ["a", "b", "", "c"]
Is a list of strings.
l = ["N" if not x else x for x in l]
Is a list of strings with empty strings replaced with "N"