The Unfun Cat
The Unfun Cat

Reputation: 31898

Replace one string in a list of strings

I have a list of strings.

If one of the strings (e.g. at index 5) is the empty string, I want to replace it with "N".

How do I do that? The naive method (for a java programmer) does not work:

string_list[5] = "N"

gives

'str' object does not support item assignment

(string_list originally came from a .csv-file- that is why it might contain empty strings.)

Upvotes: 2

Views: 23797

Answers (5)

Estatistics
Estatistics

Reputation: 946

The following example iterates through lists of lists (sublists), in order to replace a string, a word:

myoldlist=[['aa bbbbb'],['dd myword'],['aa myword']]
mynewlist=[]
for i in xrange(0,3,1):
    mynewlist.append([x.replace('myword', 'new_word') for x in myoldlist[i]])

print mynewlist
# ['aa bbbbb'],['dd new_word'],['aa new_word']

Upvotes: 0

Aesthete
Aesthete

Reputation: 18850

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"

Upvotes: 2

RocketDonkey
RocketDonkey

Reputation: 37249

Try this:

>>> s = 'abc de'
>>> s.replace(' ', 'N')
'abcNde'

As mentioned by the others, it sounds like string_list is actually a string itself, meaning that you can't use assignment to change a character.

Upvotes: 1

Next Door Engineer
Next Door Engineer

Reputation: 2876

In python work with lists and convert them to strings when need be.

>> str = list("Hellp")

>> str
['H', 'e', 'l', 'l', 'p']

>> str[4] = 'o'

>> str
['H', 'e', 'l', 'l', 'o']

TO make it a string use

>> "".join(str)

'Hello World'

Python strings are immutable and they cannot be modified.

Or you could use List Comprehensions.

Some thing like:

>> myStr = ['how', 'are', 'yew', '?']

>> myStr = [w.replace('yew', 'you') for w in myStr]

Upvotes: 0

Cédric Julien
Cédric Julien

Reputation: 80761

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"]

Upvotes: 5

Related Questions