2014-07-03 3 views
0

C'est peut-être une question idiote mais j'aimerais savoir comment les autres s'en occupent ou s'il y a une façon standard/recommandée de s'y prendre. Vous trouverez ci-dessous deux approches pour diviser une longue ligne de texte lors de l'impression en écran python. Lequel devrait être utilisé?Fractionner une longue ligne imprimée pour afficher le bon chemin en python

Option 1

if some_condition: # Senseless indenting. 
    if another condition: # Senseless indenting. 
     print 'This is a very long line of text that goes beyond the 80\n\ 
character limit.' 

Option 2

if some_condition: # Senseless indenting. 
    if another condition: # Senseless indenting. 
     print 'This is a very long line of text that goes beyond the 80' 
     print 'character limit.' 

Personnellement, je trouve Option 1 laid, mais Option 2 semble que ce serait aller à l'encontre de la façon pythonique de garder choses simples en utilisant un deuxième appel print.

+2

Personnellement, j'utiliser citant triple. – Max

Répondre

2

Une façon de le faire peut être entre parenthèses:

print ('This is a very long line of text that goes beyond the 80\n' 
     'character limit.') 

Bien sûr, il y a plusieurs façons de le faire. Une autre façon (comme suggéré dans les commentaires) est la triple citation:

print '''This is a very long line of text that goes beyond the 80 
character limit.''' 

Personnellement, je n'aime pas que l'on beaucoup parce qu'il semble casser l'empreinte, mais qui est juste moi.

+1

+1 Battez-moi. –

+0

Pourtant, en quelque sorte upvote le vôtre d'abord :) –

1

Si vous avez une chaîne longue et que vous souhaitez insérer des sauts de ligne aux points appropriés, le module textwrap fournit des fonctionnalités pour cela. Ex:

import textwrap 

def format_long_string(long_string): 
    wrapper = textwrap.TextWrapper() 
    wrapper.width = 80 
    return wrapper.fill(long_string) 

long_string = ('This is a really long string that is raw and unformatted ' 
       'that may need to be broken up into little bits') 

print format_long_string(long_string) 

Il en résulte ce qui suit en cours d'impression:

This is a really long string that is raw and unformatted that may need to be 
broken up into little bits 
Questions connexes