0

我正在尝试通过使用 google python 样式 rc 文件在其上运行 pylint 来清理我的分配代码。我只是想确认这是第一行打印的正确样式,因为它看起来很奇怪,但是 google 样式 rcfile 显示它是正确的样式。我知道每行的长度不能超过 80 个字符

for position, length in STEPS:
    guess = prompt_guess(position, length)
    score = compute_score(guess, position, word)
    total = + total + score
    print("Your guess and score were: " + ('_' * position + str(guess) +
                                           ('_' * (len(word) - length -
                                                   position))) + " : " +
          str(score))
    print("")

我会像这样格式化它:

for position, length in STEPS:
    guess = prompt_guess(position, length)
    score = compute_score(guess, position, word)
    total = + total + score
    print("Your guess and score were: " + ('_' * position + str(guess) +
         ('_' * (len(word) - length -position))) + " : " + str(score))
    print("")

任何澄清将不胜感激,谢谢

4

3 回答 3

1

你不应该在里面建立你的字符串print。当涉及到很长的消息时,请采取几个步骤来构建它。

s = "Your guess and score were: "
s += '_' * position
s += str(guess)
s += '_' * (len(word) - length - position)
s += " : "
s += str(score))

str.format您可以使用该方法使其更清洁。根据给定的名称,参数将替换花括号:

pad1 = '_' * position
pad2 = '_' * (len(word) - length - position)
s = "Your guess and score were: {pad1}{guess}{pad2} : {score}"
s = s.format(pad1=pad1, pad2=pad2, guess=guess, score=score)

这允许您将参数缩进为列表,以防它们的名称很长:

s = s.format(pad1=pad1,
             pad2=pad2,
             guess=guess,
             score=score)

如果每个参数的定义足够短,您可以将其发送给format方法:

s = "Your guess and score were: {pad1}{guess}{pad2} : {score}"
s = s.format(pad1='_' * position,
             pad2='_' * (len(word) - length - position),
             guess=guess,
             score=score)

如果你的字符串有很多值需要插值,你可以去掉变量名,但是,花括号将被参数以相同的顺序替换:

s = "Your guess and score were: {}{}{} : {}"
s = s.format(pad1, guess, pad2, score)
于 2017-08-21T15:29:38.850 回答
0

参见PEP-8 关于缩进

# YES: Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# NO: Arguments on first line forbidden when not using vertical alignment.
foo = long_function_name(var_one, var_two,
    var_three, var_four)

(与缩进的 Google Python 样式指南一致。)

另外,应该在二元运算符之前还是之后换行?

# NO: operators sit far away from their operands
income = (gross_wages +
          taxable_interest +
          (dividends - qualified_dividends) -
          ira_deduction -
          student_loan_interest)

# YES: easy to match operators with operands
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)
于 2017-08-21T15:21:12.613 回答
0

正确,缩进取决于前一行的括号。但可读性不仅仅是通过 pylint,请考虑:

print("Your guess and score were: {PAD1}{GUESS}{PAD2} : {SCORE}"
      "".format(PAD1='_' * position,
                GUESS=guess,
                PAD2='_' * (len(word) - length - position),
                SCORE=score))

(使用字符串连接可以更轻松地格式化较长的字符串。)

于 2017-08-21T15:31:16.537 回答