TypeError:字符串索引必须是整数,而不是str 4

2024-05-14 19:25:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着做一个代码,简单地把一个“o”放在任何给定单词的每个辅音前面,我不知道从这里到哪里去,我只得到一个错误"TypeError: string indices must be integers, not str"

k = list('b' + 'c' + 'd' + 'f' + 'g' + 'h' + 'j' + 'k' + 'l' + 'm' + 'n' + 'p' + 'q' + 'r' + 's' + 't' + 'v' + 'w' + 'x' + 'z')
for bok in k:
    text = list(raw_input("Give a phrase to code: "))
    print bok["0"]

Tags: integers代码forstring错误notbe单词
3条回答

首先,数组索引是用整数而不是字符串来完成的:

>>> a = [1, 2, 3]
>>> a["0"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> a[0]
1

其次,您可以在不使用太多+的情况下生成字符串:

^{pr2}$

第三,可以迭代字符串而不必将其转换为列表:

>>> for c in list("abc"):
...     print c
... 
a
b    
c
>>> for c in "abc":
...     print c
... 
a
b        
c

第四,遍历一个字符串可以得到一个包含每个字符的字符串。您不必获取该字符串的第0个索引-这是相同的:

>>> "b"
'b'
>>> "b"[0]
'b'
>>> "b"[0] == "b"
True

您使用的是print bok["0"],使用字符串“0”作为索引。你需要用整数来替换:

  print bok[0]

我不确定我是否理解您的总体目标,但这将解决您发布此问题的错误。在

更简单的方法是使用正则表达式,例如:

import re

print re.sub('([bcdfghjklmnpqrstvwxyz])', r'o\1', 'tobias')
# otoobiaos

这将查找[](辅音)之间的任何一个,并将其替换为o,后跟找到的字母。在

例如,获取用户输入:

^{pr2}$

相关问题 更多 >

    热门问题