简体   繁体   中英

Save the index value of blanks in a string to a tuple in Python 3

How can I save the index position of spaces in a text sentence to a tuple so I can reconvert the sentence back after removing the strings?

For example in this text the are spaces which causes an error as there are no space in the ascii alphabet. So I want to remove the spaces, convert and then reformat spaces back to original position.

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)

If you want to know the indices of all the blanks, I suppose using enumerate could be helpful:

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

(This gives a list instead of a tuple , but it's not hard to get the tuple if you really need it...)

With that said, looping over a string character-by-character, is not the best way to accomplish most tasks in python. It's hard for me to tell exactly what transform you're trying to perform on the string, so I'm not sure how to advise better ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM