将字符串中空格的索引值保存到Python 3中的元组中

2024-10-04 11:24:37 发布

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

如何将文本句子中空格的索引位置保存到元组中,以便在删除字符串后重新转换句子

例如,在本文中,空格会导致错误,因为ascii字母表中没有空格。所以我想删除空格,转换,然后重新格式化,回到原来的位置

import string

text = "This is the text I wish to convert"

alpha = [c for c in list(string.ascii_lowercase)]
alphaTup = tuple(alpha)

myConvert = list(text.lower())

blanks = myConvert.index(' ')
print(blanks)
# This doesn't work
for item in myConvert:
    #find index of item in alphaTup and return value at index + 1
    newLet = alphaTup[alphaTup.index(item) + 1]
    print(newLet)

Tags: textinalphaforstringindexasciithis
1条回答
网友
1楼 · 发布于 2024-10-04 11:24:37

如果您想知道所有空格的索引,我想使用^{}可能会有帮助:

blank_indices = [i for i, c in enumerate(text) if c == ' ']

(这提供了一个list而不是一个tuple,但是如果你真的需要它的话,获得tuple并不难…)

话虽如此,在python中,逐个字符串循环并不是完成大多数任务的最佳方式。对于我来说,很难准确地说出您试图对字符串执行的转换,所以我不知道如何更好地建议

相关问题 更多 >