【问题标题】:Indentation under wrapped line换行下的缩进
【发布时间】:2023-03-23 12:09:01
【问题描述】:

我开始编程和使用 Pycharm。我采用 79 行作为最大行长。但现在我不知道是否使用额外的制表符来缩进下一行,因为上一行已经在第一行下缩进了。这说明了我的意思:

我可以用这个:

if len(word) % 2 == 1:
    cent = len(word) // 2
    if (word[cent] == 'a' or word[cent] == 'e' or word[cent] == 'i'
            or word[cent] == 'o' or word[cent] == 'u'):
                print('The word's center is a lowercase vowel')

或者这个:

if len(word) % 2 == 1:
    cent = len(word) // 2
    if (word[cent] == 'a' or word[cent] == 'e' or word[cent] == 'i'
            or word[cent] == 'o' or word[cent] == 'u'):
        print('The word's center is a lowercase vowel')

任何一种方式都有效。

那么,是否有针对这些情况的约定。 提前谢谢大家! 祝你有美好的一天:)

【问题讨论】:

标签: python-3.x indentation word-wrap ident


【解决方案1】:

每个 PEP8 https://www.python.org/dev/peps/pep-0008/#maximum-line-length:

包装长行的首选方法是在圆括号、方括号和大括号内使用 Python 隐含的续行。通过将表达式括在括号中,可以将长行分成多行。应该优先使用这些,而不是使用反斜杠来续行。

至于后续行的缩进,包括更多缩进以区别于其他行。:

https://www.python.org/dev/peps/pep-0008/#indentation

代码如下所示:

if len(word) % 2 == 1:
    cent = len(word) // 2
    if (word[cent] == 'a' or word[cent] == 'e' or word[cent] == 'i'
            or word[cent] == 'o' or word[cent] == 'u'):
        print("The word's center is a lowercase vowel")

【讨论】:

    【解决方案2】:

    您可以使用\ 作为一行中的最后一个字符来表示“这一行在下一行继续” - 这有助于“正常”python 代码不能被破坏(不是你的情况)。

    你的例子更适合

    vowels = set("aeiou") # maybe faster then list-lookup if used several times
    if word[cent] in vowels:
    

    或通过

    if word[cent] in "aeiou":
    

    或通过

    def isVowel(ch):
        return ch in "aeiou"
    
    if isVowel(word[cent]):
    

    PEP-8 maximum line lenght 讲述如何“正确格式化”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-25
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      • 1970-01-01
      • 2015-08-05
      相关资源
      最近更新 更多