gpt4 book ai didi

python - 使用 Python str.splitlines() 处理尾随换行符

转载 作者:行者123 更新时间:2023-12-01 09:06:24 27 4
gpt4 key购买 nike

我正在图像上实现文本绘制,并尝试通过实现适当前进的“文本光标”来处理换行符。

我有一个处理尾随换行符的解决方案,但它很丑陋且不符合 Python 风格。 Pythonic 方式是什么?

这就是我现在正在做的事情(出于示例目的的简化代码):

# string may contain zero or more newlines, may or may not terminate in a newline

def text(string):

for line in string.splitlines():

global x_cursor, y_cursor # pixel location of cursor in image

x_size_of_text = draw_one_line_of_text(line)
old_x_cursor = x_cursor

x_cursor = 0
y_cursor += 20 # lines are 20 pixels high

if string[-1] != '\n': # if no trailing newline, undo final newline

x_cursor = old_x_cursor + x_size_of_text
y_cursor -= 20

我在 string.splitline() 返回的每一行之后执行换行符,然后如果原始字符串未以换行符终止,则撤消换行符。

这可行,但很难看。正确的做法是什么?

最佳答案

您可以告诉 splitlines 在分割时保留行尾(通过传递 True 作为可选参数)。

然后,在每一行上,如果没有换行符,则不要转到下一行(显示时必须剥离 line

对于 string.splitlines(True) 中的行:

    global x_cursor, y_cursor           # pixel location of cursor in image

x_size_of_text = draw_one_line_of_text(line.rstrip())
old_x_cursor = x_cursor
if line.endswith("\n"):
x_cursor = 0
y_cursor += 20 # lines are 20 pixels high

这避免了最终测试,但引入了很多额外的测试和复杂性,只是为了处理最后一种情况。我认为坚持您的解决方案没有问题(它很丑陋但速度很快 - 最好请求宽恕而不是许可)。

一个反对意见,而不是:

if string[-1] != '\n':  # if string is empty: Index out of range exception

我会这样做:

if string and not string.endswith("\n"):

如果字符串为空,您的测试将使您的程序崩溃。此外,没有什么需要纠正的,所以首先测试空字符串。

关于python - 使用 Python str.splitlines() 处理尾随换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52010637/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com