How can I do a line break (line continuation) in Python?

后端 未结 11 1599
囚心锁ツ
囚心锁ツ 2020-11-21 22:56

I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?

For example, adding a bunch of strings,



        
11条回答
  •  花落未央
    2020-11-21 23:35

    Use the line continuation operator i.e. "\"

    Examples:

    # Ex.1
    
    x = 1
    s =  x + x**2/2 + x**3/3 \
           + x**4/4 + x**5/5 \
           + x**6/6 + x**7/7 \
           + x**8/8
    print(s)
    # 2.7178571428571425
    
    
    ----------
    
    
    # Ex.2
    
    text = ('Put several strings within parentheses ' \
            'to have them joined together.')
    print(text)
    
    
    ----------
    
    
    # Ex.3
    
    x = 1
    s =  x + x**2/2 \
           + x**3/3 \
           + x**4/4 \
           + x**6/6 \
           + x**8/8
    print(s)
    # 2.3749999999999996
    

提交回复
热议问题