我必须在由该行的行号和字号指定的特定位置替换多行文本中的一个单词。所有单词都在列中对齐。
我正在使用一种算法,通过它的坐标来查找单词。
我在指定的行号获取一行,将其拆分成单独的子串,并将指定位置的一个单词替换为另一个单词。然后我连接(“".join() )并将修改后的行写回到一个文件中。我的问题是我在修改后的行中失去了单词对齐。我怎样才能同时证明和加入呢?(一行中的其他单词也会丢失对齐,而不仅仅是修改后的单词)
我想,如果我使用稍微不同的方法,在要修改的单词位置拆分一行,我可以做到这一点,但我没有意识到,在单词边界拆分一行后,我会失去对齐。
发布于 2013-03-18 06:19:47
在连接之前,您可以在列表理解中应用格式(使用format()或str.format()):
''.join([format(el, '<10') for el in list_of_strings])演示:
>>> list_of_strings = ['foo', 'barbaz', 'spam-ham']
>>> ''.join([format(el, '<10') for el in list_of_strings])
'foo barbaz spam-ham '<左对齐、>右对齐和^在给定宽度(上例中为10)内居中对齐文本。有关格式化如何工作的更多详细信息,请参阅format specification documentation。
向右调整为4个空格的Demo:
>>> list_of_strings = ['foo', 'ba', 'a']
>>> ''.join([format(el, '>4') for el in list_of_strings])
' foo ba a'发布于 2013-03-18 06:23:57
您可以尝试使用re.split进行拆分。如果您使用/(?<= )\w/作为正则表达式,它将在每个单词之前拆分,同时保留空格。然后,您可以在替换该单词后使用''.join(...)加入它们。你可以根据需要在新单词后面加上任意多的空格,只需询问旧单词的长度。
请注意,如果新单词的长度大于列的宽度,则会出现错误。
如果我用代码写出这段代码:
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)发布于 2013-03-18 06:25:37
str = "this is a sample statement";
print str.rjust(50, ' '); # right justification这将产生以下结果:
**中国*,这是一个示例声明。
后跟语句的50空格
你可以试试
print str.rjust(0, ' ')强制判决是正确的。
https://stackoverflow.com/questions/15466859
复制相似问题