سؤال

I have to replace a word in a multiline text at specific location specified by a line number and word number in this line. All words all aligned in columns.

I'm using an algorithm where I'm finding word by it's coordinates.

I'm fetching a line at specified line number, splitting it in separate substrins and replacing a word at specified location with another word. Then I do join (" ".join() ) and writing the modified line back into a file. My problem is i'm loosing words alignment in modified line. How can I justify and join at the same time? (Other words in a line also lose alignment, not just modified word)

I think I could do it if I have used a little bit different approach by splitting a line just at the location of the word to be modified, but I did not realized that I will lose alignment after splitting a line at word boundaries.

هل كانت مفيدة؟

المحلول

You can apply formatting (with format() or str.format()) inside a list comprehension before joining:

''.join([format(el, '<10') for el in list_of_strings])

Demo:

>>> list_of_strings = ['foo', 'barbaz', 'spam-ham']
>>> ''.join([format(el, '<10') for el in list_of_strings])
'foo       barbaz    spam-ham  '

< left-aligns, > right-aligns and ^ centers the text in the given width (10 in the above example). For more detail on how formatting works, see the format specification documentation.

Demo with right-adjustment to 4 spaces:

>>> list_of_strings = ['foo', 'ba', 'a']
>>> ''.join([format(el, '>4') for el in list_of_strings])
' foo  ba   a'

نصائح أخرى

str = "this is a sample statement";

print str.rjust(50, ' '); # right justification

this will produce the following result:
                                                   this is a sample statement

50 blank spaces followed by your statement

you can try

print str.rjust(0, ' ')

to force sentences to be right justified.

You could try splitting with re.split instead. If you use /(?<= )\w/ as Regex, it'll split before each word, while preserving the whitespace. You can then join them with ''.join(...) after replacing the word. You can append the new word with as much spaces as needed, just ask the length of the old word.

Note that this will bug if the new word is longer then the column is wide.

If I write this out in code:

col = 1                              # replacing second word
line = "hello  there    friend    "  # we've already fetched the line
new_word = "here"                    # the new word
word_list = re.split('(?<= )\w', line)
length = len(word_list[col])
word_list[col] = col + ((length - len(new_word)) * ' ')
new_line = ''.join(word_list)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top