相关疑难解决方法(0)

字符串格式化[str.format()],带有字典键,它是数字的str()

Python新手在这里.我想知道是否有人可以帮助KeyError我在使用字典进行字符串插值时得到的str.format.

dictionary = {'key1': 'val1', '1': 'val2'}

string1 = 'Interpolating {0[key1]}'.format(dictionary)
print string1
Run Code Online (Sandbox Code Playgroud)

以上工作正常,产量:

Interpolating val1
Run Code Online (Sandbox Code Playgroud)

但是请执行以下操作:

dictionary = {'key1': 'val1', '1': 'val2'}

string2 = 'Interpolating {0[1]}'.format(dictionary)
print string2
Run Code Online (Sandbox Code Playgroud)

结果是:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    string2 = 'Interpolating {0[1]}'.format(dictionary)
KeyError: 1L
Run Code Online (Sandbox Code Playgroud)

所以问题似乎在于将数字键解释为列表索引,恕我直言. 有什么方法可以解决这个问题吗? (即传达这是一个字典键)

如果之前已经问过这个问题,TIA并道歉(找不到与我的搜索相关的任何内容).

编辑1:密钥不是数字,正如之前错误记录的那样.相反,它是一个数字的字符串表示 - 正如BrenBarn所指出的那样.

python python-2.7

12
推荐指数
2
解决办法
2万
查看次数

如何在 Python 字符串中替换括号和文本

我有两个这样的字符串。

string1 = "Today I went to the (market) to pick up some (fruit)."
string2 = "Today I went to (school) to learn (algebra) and science."
Run Code Online (Sandbox Code Playgroud)

我想根据以下字典删除并替换两个字符串中的括号和括号内的文本。

word_dict = {'market': 'library', 'fruit': 'books', 'school': 'class', 'algebra': 'calculus'};
Run Code Online (Sandbox Code Playgroud)

我希望新字符串是:

string1 = "Today I went to the library to pick up some books."
string2 = "Today I went to class to learn calculus and science."
Run Code Online (Sandbox Code Playgroud)

为了做到这一点,我需要捕获括号内的文本,以便我可以将其用作获取字典中值的键。然后我需要用该值替换括号和文本。我在使用正则表达式以及如何执行此操作时遇到问题。

python regex string

3
推荐指数
1
解决办法
4337
查看次数

标签 统计

python ×2

python-2.7 ×1

regex ×1

string ×1