获取多行字符串的索引

2024-04-26 18:43:57 发布

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

尝试在多行字符串中获取值与其索引相同的整数。这是我的审判

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

如果我执行上述命令,我将得到一个3而不是4的输出。 我正在尝试用print获取数字I(表[I])

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


Tags: 方法字符串命令table情况数字整数list
1条回答
网友
1楼 · 发布于 2024-04-26 18:43:57

您的字符串在位置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

在旁注上-如果您的表没有更改为始终跳过替换字符串中的填充,则可能需要构建查找dict:

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”字符串

相关问题 更多 >