Asked  7 Months ago    Answers:  5   Viewed   32 times

This simple code that simply tries to replace semicolons (at i-specified postions) by colons does not work:

for i in range(0,len(line)):
     if (line[i]==";" and i in rightindexarray):

It gives the error

TypeError: 'str' object does not support item assignment

How can I work around this to replace the semicolons by colons? Using replace does not work as that function takes no index- there might be some semicolons I do not want to replace.


In the string I might have any number of semicolons, eg "Hei der! ; Hello there ;!;"

I know which ones I want to replace (I have their index in the string). Using replace does not work as I'm not able to use an index with it.



Strings in python are immutable, so you cannot treat them as a list and assign to indices.

Use .replace() instead:

line = line.replace(';', ':')

If you need to replace only certain semicolons, you'll need to be more specific. You could use slicing to isolate the section of the string to replace in:

line = line[:10].replace(';', ':') + line[10:]

That'll replace all semi-colons in the first 10 characters of the string.

Tuesday, June 1, 2021
answered 7 Months ago

The easiest would be to use a regular expression with g flag to replace all instances:

str.replace(/foo/g, "bar")

This will replace all occurrences of foo with bar in the string str. If you just have a string, you can convert it to a RegExp object like this:

var pattern = "foobar",
    re = new RegExp(pattern, "g");
Tuesday, June 1, 2021
answered 7 Months ago

You need to use a regular expression, so that you can specify the global (g) flag:

var s = 'some+multi+word+string'.replace(/+/g, ' ');

(I removed the $() around the string, as replace is not a jQuery method, so that won't work at all.)

Saturday, June 12, 2021
answered 6 Months ago

You can use bytes literal: b'key'

def _generate_signature(data):
    return'key', data, hashlib.sha256).hexdigest()

In addition to that, make sure data is also bytes. For example, if it is read from file, you need to use binary mode (rb) when opening the file.

Wednesday, July 28, 2021
answered 4 Months ago

StringIO documentation:

Unlike the memory files implemented by the StringIO module, those provided by [cStringIO] are not able to accept Unicode strings that cannot be encoded as plain ASCII strings.

If possible, use StringIO instead of cStringIO.

Monday, August 9, 2021
Michal Charemza
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :