简体   繁体   中英

How to replace a list of words with a string and keep the formatting in python?

I have a list containing the lines of a file.

list1[0]="this is the first line"
list2[1]="this is the second line"

I also have a string.

example="TTTTTTTaaaaaaaaaabcccddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeefffff"

I want to replace list[0] with the string (example). However I want to keep the word length. For example the new list1[0] should be "TTTT TT TTa aaaaa aaaa" . The only solution I could come up with was to turn the string example into a list and use a for loop to read letter by letter from the string list into the original list.

for line in open(input, 'r'):
        list1[i] = listString[i]
        i=i+1

However this does not work from what I understand because Python strings are immutable? What's a good way for a beginner to approach this problem?

I'd probably do something like:

orig = "this is the first line"
repl = "TTTTTTTaaaaaaaaaabcccddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeefffff"

def replace(orig, repl):
    r = iter(repl)
    result = ''.join([' ' if ch.isspace() else next(r) for ch in orig])
    return result

If repl could be shorter than orig , consider r = itertools.cycle(repl)

This works by creating an iterator out of the replacement string, then iterating over the original string, keeping the spaces, but using the next character from the replacement string instead of any non-space characters.

The other approach you could take would be to note the indexes of the spaces in one pass through orig , then insert them at those indexes in a pass of repl and return a slice of the result

def replace(orig, repl):
    spaces = [idx for idx,ch in enumerate(orig) if ch.isspace()]
    repl = list(repl)
    for idx in spaces:
        repl.insert(idx, " ")
        # add a space before that index
    return ''.join(repl[:len(orig)])

However I couldn't imagine the second approach to be any faster, is certain to be less memory-efficient, and I don't find it easier to read (in fact I find it HARDER to read!) It also don't have a simple workaround if repl is shorter than orig (I guess you could do repl *= 2 but that's uglier than sin and still doesn't guarantee it'll work)

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