Replace string does not work

First I tried using the = operator to assign a 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 returns the value of orignal.

Learn how to use the replacement API correctly to give the correct result. There is also some other API that can be used instead of unichr() .

encrypted_str is taken from the user encrypted_str = raw_input() dec_str2 is the freq string entered by the user. The question is hardly related to the variable. I want to know if I am using the replcae() API replcae() , since it gives me immutable output for encrypted_str Can we use encrypted_str[j] to return a character from a string to define a substring 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 (since I only need one replacement).

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

Since I'm new to python, I'm trying to find a replacement.

+6
source share
2 answers

Strings in Python are immutable. This means that the given string object will never change its value after its creation. This is why assigning an element as some_str[4] = "x" will throw an exception.

For the same reason, none of the methods provided by the str class can modify a string. Thus, the str.replace method does not work as I think you expect it. Instead of changing 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 intend to make many such replacements, it might make sense to turn your string into a list of characters, make changes one by one, and then use str.join to include the list in the string again when you are done.

+19
source

Python strings are immutable. This means that the string cannot be changed by calling the method as described in your post. You must use assignment to use the returned string in the method call.

For instance:

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

encrypted_str now contains the new value.

+3
source

Source: https://habr.com/ru/post/978231/


All Articles