Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the spaces in a string format in Python 3

How can I set up the string format so that I could use a variable to ensure the length can change as needed? For example, lets say the length was 10 at first, then the input changes then length becomes 15. How would I get the format string to update?

    length =  0
    for i in self.rows:
        for j in i:
            if len(j) > length:
                length  = len(j)
    print('% length s')

Obviously the syntax above is wrong but I can't figure out how to get this to work.

like image 847
uhexos Avatar asked Mar 21 '16 18:03

uhexos


People also ask

How do you put a space in a string in Python?

To add spaces between the characters of a string: Call the join() method on a string containing a space. Pass the string as an argument to the join method. The method will return a string where the characters are separated by a space.

How do you put a space in a string format?

Use the String. format() method to pad the string with spaces on left and right, and then replace these spaces with the given character using String. replace() method. For left padding, the syntax to use the String.

What is .2f in Python?

As expected, the floating point number (1.9876) was rounded up to two decimal places – 1.99. So %. 2f means to round up to two decimal places. You can play around with the code to see what happens as you change the number in the formatter.


1 Answers

Using str.format

>>> length = 20
>>> string = "some string"
>>> print('{1:>{0}}'.format(length, string))
         some string
like image 73
OneCricketeer Avatar answered Sep 19 '22 22:09

OneCricketeer