Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String replace doesn't appear to be working

I initially tried using = operator to assign value but it returned an error, then I tried using string.replace():

encrypted_str.replace(encrypted_str[j], dec_str2[k], 2)

and

encrypted_str.replace(encrypted_str[j], unichr(ord(dec_str2[k]) - 32), 2)

But it is returning the orignal value.

Help out as to how to use the replace API properly to give the correct result Also is there any other API that can be used instead of unichr().

The encrypted_str is being taken from the user by encrypted_str = raw_input() dec_str2 is the freq string being input by user. The issue hardly concerns the variable I want to know if I am using the replcae() API incorrectly as it is giving me unchanged output for encrypted_str Can we use encrypted_str[j] would return a character from the string to define the sub string for the replace() API. I used encrypted_str.replace(encrypted_str[j], unichr(ord(dec_str2[k]) - 32), 1) max replace 1 instead of 2 (as I need just the one replacement).

The actual operation that I need to be done will be in C as follows: encrypted_str[j] = dec_str2[k] -32.

As I am new to python I am trying to find a substitute.

like image 767
vatsalya_mathur Avatar asked Nov 15 '14 06:11

vatsalya_mathur


2 Answers

Strings in Python are immutable. That means that a given string object will never have its value changed after it has been created. This is why an element assignment like some_str[4] = "x" will raise an exception.

For a similar reason, none of the methods provided by the str class can mutate the string. So, the str.replace method does not work the way I think you expect it to. Rather than modifying the string in place, it returns a new string with the requested replacements.

Try:

encrypted_str = encrypted_str.replace(encrypted_str[j], dec_str2[k], 2)

If you're going to be making many such replacements, it may make sense to turn your string into a list of characters, make the modifications one by one, then use str.join to turn the list back into a string again when you're done.

like image 141
Blckknght Avatar answered Oct 05 '22 15:10

Blckknght


Python strings are immutable. This means that a string cannot be modified by a method call as described in your post. You must use an assignment in order to use the returned string from your method call.

For example:

encrypted_str = encrypted_str.replace(encrypted_str[j], dec_str2[k], 2)

Now encrypted_str contains the new value.

like image 42
grovesNL Avatar answered Oct 05 '22 15:10

grovesNL