[英]Save the index value of blanks in a string to a tuple in Python 3
如何将文本句子中空格的索引位置保存到元组,以便在删除字符串后可以将句子重新转换回原来的位置?
例如,在本文中,空格会引起错误,因为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)
如果您想知道所有空格的索引,我想使用enumerate
可能会有所帮助:
blank_indices = [i for i, c in enumerate(text) if c == ' ']
(这给出了一个list
而不是一个tuple
,但是如果您确实需要它,获取tuple
并不难...)
话虽如此,逐个字符地循环一个字符串,并不是在python中完成大多数任务的最佳方法。 对于我来说,很难确切说明您要对字符串执行哪种转换,因此我不确定如何建议更好...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.