首页 > 解决方案 > 获取多行字符串的索引

问题描述

试图在多行字符串中获取一个整数,其值与其索引相同。这是我的试验。

table='''012
345
678'''
print (table[4])

如果我执行上述操作,我将得到 3 而不是 4 的输出。我正在尝试使用 print(table[i]) 获取数字 i

在不使用列表的情况下获取与 table[i] 对应的数字的最简单方法是什么,因为稍后我必须进一步使用 while 循环来替换表的值并且使用列表会非常麻烦。谢谢。

标签: pythonpython-3.xstring

解决方案


您的字符串在位置 4 包含空格(回车和 mabye 换行)(在 linux 中为 \n,在 Windows 上为 4+5 上的 \n\r) - 您可以通过删除它们来清理文本:

table='''012
345
678'''
print (table[4]) #3 - because [3] == \n
print(table.replace("\n","")[4])  # 4

您可以像这样查看“表格”中的所有字符:

print(repr(table))
# print the ordinal value of the character and the character if a letter
for c in table:
    print(ord(c), c if ord(c)>31 else "")

输出:

'012\n345\n678'

48 0
49 1
50 2
10 
51 3
52 4
53 5
10 
54 6
55 7
56 8

在旁注中 - 如果您的表没有更改为一直跳过替换字符串中的内容,您可能想要构建一个查找字典:

table='''012
345
678'''

indexes = dict( enumerate(table.replace("\n","")))
print(indexes)

输出:

{0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8'}

所以你可以做得到index[3]'3'字符串


推荐阅读