字符串替换似乎不起作用 [英] String replace doesn't appear to be working

查看:63
本文介绍了字符串替换似乎不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最初尝试使用 = 运算符来赋值,但它返回了一个错误,然后我尝试使用 string.replace():

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)

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

但它正在返回原始值.

帮助了解如何正确使用替换 API 以给出正确的结果还有没有其他 API 可以代替 unichr().

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().

encrypted_str 正在通过 encrypted_str = raw_input() 从用户那里获取dec_str2 是用户输入的频率字符串.这个问题几乎不涉及变量我想知道我是否错误地使用了 replcae() API,因为它给了我 encrypted_str 不变的输出我们可以使用 encrypted_str[j] 从字符串中返回一个字符 来定义 replace() API 的子字符串吗?我使用了 encrypted_str.replace(encrypted_str[j], unichr(ord(dec_str2[k]) - 32), 1) ma​​x replace 1而不是 2(因为我只需要一个替换).

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).

我需要在C中进行的实际操作如下:encrypted_str[j] = dec_str2[k] -32.

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

由于我是 Python 新手,我正在尝试寻找替代品.

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

推荐答案

Python 中的字符串是不可变的.这意味着给定的字符串对象在创建后永远不会更改其值.这就是像 some_str[4] = "x" 这样的元素赋值会引发异常的原因.

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.

出于类似的原因,str 类提供的任何方法都不能改变字符串.所以, str.replace 方法并没有像我认为的那样工作.它不是在原地修改字符串,而是返回一个带有请求替换的新字符串.

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.

试试:

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

如果你要进行很多这样的替换,把你的字符串变成一个字符列表,一个一个地进行修改,然后使用 str.join 来转换可能是有意义的完成后,将列表重新转换为字符串.

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.

这篇关于字符串替换似乎不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆