PYTHON PROGRAMMING. PART II: PYTHON OBJECTS AND DATA STRUCTURE BASICS. UNIT 3: STRING. PART II: STRING FORMATTING

     PYTHON PROGRAMMING

 PART II: PYTHON OBJECTS AND DATA STRUCTURE BASICS

UNIT 3: STRING

PART 2: STRING FORMATTING

    In Python, we are having 3 methods to format strings, up to now. They are:

- Formatting with placeholders

- Formatting with the .format() method

- Formatting with Formatted-string (f-string) ( introduced in Python 3.6)

I. Formatting with placeholders:

       - Use modulo % (string formatting operator) 

                print("Inject %s text here, and %s text here"%('some', 'more')

                    => Inject some text here, and more text here

       - You can also pass variables.

                x = 'khiem'

                print("Inject %s" %(x))

                    => Inject khiem

    a) Formatting conversion method

            %s using str()

            %r using repr() (string representation)

                print("I'm %s " %('Khiem'))

                    => I'm Khiem

                print("I'm %r" %('Khiem'))

                    => I'm 'Khiem'

            You can insert tab by using \t or insert newline using \n

                print("I once caught a fish %s." %'this \t big')

                    => I once caught a fish this    big.

                print(""I once caught a fish %r." %'this \t big')

                    => I once caught a fish this \t big.

            %d converts numbers into integers, without rounding.

     b) Padding and Precision of floating-point numbers.

    

            Example:    print('%5.2f'%(13.144))

                                  => 13.14

            Explanation:

                5 would be the minimum number of characters the string should contain, these may be padded with whitespace if the entire number does not have this many digits.

                .2f stands for how many numbers to show past the decimal point.

II. Formatting with the .format() method.

                print('Insert {} '.format('something'))

                    => Insert something

    a) Inserted objects can be called by index position.

                print('The {2} {1} {0}'.format('fox', 'brown', 'fox'))

                    => The quick brown fox

    b) Inserted objects can be assigned keywords

                print('1st : {a}, 2nd: {b}. 3rd: {c}'.format(a = 1, b = 'Two', c = 12,3))

                    => 1st: 1, 2nd: Two, 3rd: 12.3

    c) Inserted objects can be reused, avoiding duplication

                print('A {p} saved is a {p} earned.'.format(p = 'penny'))

                    => A penny saved is a penny earned.

    d) Alignment, padding, and precision

            Within {}, you can assign field lengths, left/ right alignments, rounding parameters.

                print('{0:8} | {1:9} '.format('Fruit', 'Quantity'))

                print('{0:8} | {1:9} '.format('Apples', 3))

                print('{0:8} | {1:9} '.format('Oranges', 10))

                    => Fruit        |        Quantity

                         Apples     |                 3.0

                         Oranges     |                  10

            By default, .format() align text to the left, numbers to the right. You can pass an optional "<", "^", ">" to set a left, center or right alignment or can also precede the alignment operator with a padding character.

            Example:

                print('{0:<8} | {1:^8} | {2:>8}'.format('Left','Center','Right'))

                print('{0:<8} | {1:^8} | {2:>8}'.format(11,22,33))

                    => Left    |    Center    |    Right

                          11      |       22        |        33

            Precede the alignment with a padding character:

                print('{0:=<8} | {1:-^8} | {2:.>8}'.format('Left','Center','Right'))

                print('{0:=<8} | {1:-^8} | {2:.>8}'.format(11,22,33))

                    => Left===|----Center----|.....Right

                         11====|-------22-------|..........33

            Field widths and float precision are handled in a similar way to placeholders. These two are equivalent:

                print('This is my ten-character, two-decimal number:%10.2f' %13.579)

                print('This is my ten-character, two-decimal number:{0:10.2f}'.format(13.579))

                    => This is my ten-character, two-decimal number: 13.58

                         This is my ten-character, two-decimal number: 13.58

III. Formatted-strings Literals (f-strings)

                name = 'Khiem'

                print(f'My name is {name}')

                    => My name is Khiem        

            Pass !r to get the string representation.

                 name = 'Khiem'

                print(f'My name is {name!r}')

                    => My name is 'Khiem'  

            Float formatting follows:

                


                num = 23.45678

                print("My 10 character, four decimal number is:{0:10.4f}".format(num))

                print(f"My 10 character, four decimal number is:{num:{10}.{6}}")

                    => My 10 character, four decimal number is 23.4567

            Note that f-strings, precision prefers to the total number of digits, not just those following the decimal. This fits more closely with scientific notation and statistical analysis. Unfortunately, f-strings do not pad to the right of the decimal, even if precision allows it.

                num = 23.45

                print("My 10 character, four decimal number is:{0:10.4f}".format(num))

                print(f"My 10 character, four decimal number is:{num:{10}.{6}}")

                    => My 10 character, four decimal number is: 23.4500

                         My 10 character, four decimal number is: 23.45

            If this becomes important, you can use .format() inside an f-string

                num = 23.45

                print("My 10 character, four decimal number is:{0:10.4f}".format(num))

                print(f"My 10 character, four decimal number is:{num:10.4f}")

                    => My 10 character, four decimal number is: 23.4500

                         My 10 character, four decimal number is: 23.4500




        



Comments