python - 获取多行字符串的索引
问题描述
试图在多行字符串中获取一个整数,其值与其索引相同。这是我的试验。
table='''012
345
678'''
print (table[4])
如果我执行上述操作,我将得到 3 而不是 4 的输出。我正在尝试使用 print(table[i]) 获取数字 i
在不使用列表的情况下获取与 table[i] 对应的数字的最简单方法是什么,因为稍后我必须进一步使用 while 循环来替换表的值并且使用列表会非常麻烦。谢谢。
解决方案
您的字符串在位置 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'字符串
推荐阅读
- powerbi - 有没有办法在 DAX 中按类别创建和显示运行总计?
- java - 如何修复泛型类型参数的运行时“空指针异常”
- certificate - VLC chromecast cast 在不受信任的证书上失败
- c - 如果条件读取如何?
- javascript - 使用嵌套的 javascript 对象返回空对象
- wordpress - WordPress 滑块小部件重新定位网页
- python - 使用python运行保存在文本文件中的sql查询
- apache-kafka - 如何在 Kafka ProducerPerformance 工具中传递多线程作为参数?
- python - 如何处理来自文本文件的输入数据
- python - 默认值不适用于存在的位置和可选参数