import textwrap
def pep8_textwrap(var_name, text, parentheses=False):
'''Wrap text for code to be within 80 characters.'''
# Variable name appended with assignment operator.
var_name += ' = '
if parentheses:
var_name += '('
# Indent size to align with right side of assignment.
indent_size = len(var_name) - 1
# Create a list of wrapped text.
string_list = textwrap.wrap(text, width=75-indent_size)
# Print the variable name equals without a newline.
print(var_name, end='')
# The last line so end of iteration will be known.
last_line = len(string_list)
# Print the wrapped text for pasting into code.
for current_line, line in enumerate(string_list, 1):
if current_line == 1:
if last_line > 1 and not parentheses:
print(repr(line + ' '), '\\')
else:
print(repr(line + ' '))
elif current_line >= last_line:
if parentheses:
print(indent_size * ' ', repr(line) + ')')
else:
print(indent_size * ' ', repr(line))
else:
if parentheses:
print(indent_size * ' ', repr(line + ' '))
else:
print(indent_size * ' ', repr(line + ' '), '\\')
# Text from 1st code example.
string_name = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam"
# Call the function to print the result.
pep8_textwrap('string_name', string_name)
# Text from 3rd code example.
string_name = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, " \
"sed diam nonumy eirmod tempor invidunt ut labore et dolore magna " \
"aliquyam"
pep8_textwrap('string_name', string_name, True)
# Text from the title.
string_name = "How do you insert line breaks in strings and translations string to meet the PEP 8 requirements?"
pep8_textwrap('var', string_name, True)
重新创建分配代码的脚本解决方案。
它将结果打印到标准输出。
将赋值复制到脚本中,并使用参数调用pep8_textwrap
要分配的变量名称,文本的实际变量名称和
可选 True 用于使用括号或省略该参数以使用反斜杠
转义以继续一行到下一行。
输出:
string_name = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed ' \
'diam nonumy eirmod tempor invidunt ut labore et dolore magna ' \
'aliquyam'
string_name = ('Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed '
'diam nonumy eirmod tempor invidunt ut labore et dolore magna '
'aliquyam')
var = ('How do you insert line breaks in strings and translations string to '
'meet the PEP 8 requirements?')