在 __getitem__ Python 2.7 中将 int 转换为 str [英] Convert int into str while in __getitem__ Python 2.7

查看:36
本文介绍了在 __getitem__ Python 2.7 中将 int 转换为 str的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我有这个字符串:

Okay, i have this string:

string = "HelloWorld"

对于这个例子,我使用了一个类似的字典:

And for this example, I am using a dictionary similar to this:

dic = [{'a':'k','b':'i'},{'a':'i','b':'l'},{'a':'x','b':'n'},{'a':'q','b':'o'}]

现在.. 我需要从列表中引用字典,以便我可以更改字符串中的字符.通常我会这样做:

Now.. I need to reference a dictionary from the list, so that I can change the characters in my string. To do so normally I would just do this:

dic[#]

但在这种情况下,我还需要该字典中的一个值.现在我试过了:

But in this case I also need a value from that dictionary. Now I tried this:

dic[int(char[i[letter]])]

但我收到错误:

'int' 对象没有属性 '__getitem__'

在 StackOverflow 上搜索错误给了我答案,但它们并没有解决我的问题.

Searching for the error gives me answers here on StackOverflow, but they do not fix my problem.

推荐答案

这是我最好的水晶球猜你想要什么.你字典的键只有 ab,它们不是 HelloWorld 中的任何字符,但如果你真的有字符串中的字符作为如下键,这就是我进行替换的方式,假设您要轮换四个不同的词典:

Here's my best crystal ball guess at what you want. The keys of your dictionary are only a and b, which aren't any characters in HelloWorld, but if you actually had characters from your string as keys like the following, this is how I'd do the replacement, assuming you want to rotate through the four different dictionaries:

string = "HelloWorld"
D = [{'H':'a','o':'e','l':'i'},{'e':'b','W':'f','d':'j'},{'l':'c','o':'g'},{'l':'d','r':'h'}]
print ''.join(D[i%4][c] for i,c in enumerate(string))

输出:

abcdefghij

这篇关于在 __getitem__ Python 2.7 中将 int 转换为 str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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