Seite 1 von 1

Textformatierungen

Verfasst: Samstag 3. Mai 2014, 09:53
von duodiscus
Hallo zusammen,
ich habe mich mit Formatierungen beschäftig (Rechtsbündig, Linksbündig, Zentriert) etc.
Jetzt habe ich folgendes Programm:

Code: Alles auswählen

def formatierung():

    s = 'X'        
    for i in range(1,6):
        formatiert = s.rjust(i, 'X')
        print(formatiert)

>>> 
X
XX
XXX
XXXX
XXXXX
Das gibt mir die X so aus. Mein Ziel ist es allerdings, es genau gespiegelt, also andersherum auszugeben:
Wie bekomme ich das hin?

Re: Textformatierungen

Verfasst: Samstag 3. Mai 2014, 10:21
von snafu
Wenn ich's richtig verstanden hab:

Code: Alles auswählen

def get_triangle(width, sign='X'):
    return '\n'.join(
        (i * sign).rjust(width) for i in range(1, width + 1)
    )

print get_triangle(5)

Re: Textformatierungen

Verfasst: Samstag 3. Mai 2014, 13:28
von mutetella
Eine andere Möglichkeit ohne mehrmalige Stringmultiplikation und `format()` statt `rjust()`:

Code: Alles auswählen

def get_triangle(width, sign='X'):
    full_string = sign * width
    return '\n'.join('{full_string:>{width}.{sub_width}}'.format(
        full_string=full_string, width=width, sub_width=sub_width) for
        sub_width in range(1, width+1))
mutetella