Escape Sequences. Basic IO. String formatting.

Escape Sequences. Basic IO. String formatting.

Escape Sequences

Escape sequences are special character combinations used in strings to represent characters that cannot be typed directly.
The backslash (\) character in a string is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.
With escape sequence we can insert characters that are illegal in a string, like quotes or new line symbol.
The most used escape sequences are given bellow:
escape character result
\' Single Quote
\" Double Quote
\n New Line
\t Tab
\\ Backslash
Reference: List of recognized escape sequences in Pyhton

Examples


            print('line1\nline2')
            #line1
            #line2

            print('abc\t123')
            #abc     123

            print('John\'s pub')
            #John's pub

            # above, we can do without escape, but changing quotes
            print("John's pub")
            #John's pub
        

Basic Input/Output (I/O)

Basic Input/Output (I/O)

print() function

print() function is used for outputting data to the console.

                print(*objects, sep=' ', end='\n',file=sys.stdout, flush=False)
            
Examples

                ### basic usage
                print("Hello")
                print("World")
                #Hello
                #World


                ### Print multiple values. Note that default separator is space
                print(1,2,3)
                # 1 2 3

                # Change separator to '-'
                print(1,2,3,sep="-")
                # 1-2-3

                # Change default EOL symbol ("\n") to none. So, there will be no new line after print
                print("Hello",end="")
                print("World",end="")
                print("!")
                # HelloWorld!

            

Python input() function

input() function is used to get user input as string.

                variable = input("prompt message, to be displayed to the user: ")
            
Examples:

                name = input("Enter your name: ")
                print("Hello,", name)
            

Input always returns a string - Example

Note, that no matter what value is entered, it will be stored as a string!

                value = input("Enter a number: ")
                print("The type of the entered value is:", type(value))  # Always <class 'str'>
            
Even if you enter a number like 42, the value will be stored as a string ("42").
But you can easily convert it to numerical, using the built in functions int() or float()

                value = input("Enter a number: ")

                # Convert to integer
                integer_value = int(value)
                print("Integer value:", integer_value)
                print("Type of integer_value:", type(integer_value))

                # Convert to float
                float_value = float(value)
                print("Float value:", float_value)
                print("Type of float_value:", type(float_value))
            

Formatted Strings (f-strings)

Formatted Strings (f-strings)

Why?

Before Python 3.6 we have to use the concatenation operator when we want to display some string and some variables interpolated into it.
Consider next example:

                user_name = 'Ada'
                user_surname = 'Byron'

                print('Hello ' + user_name + ' ' + user_surname + '!')

                # Hello Ada Byron!
            
With f-strings, the code is more readable and easy to write (like using "template strings" in JavaScript):

                user_name = 'Ada'
                user_surname = 'Byron'

                print(f'Hello {user_name} {user_surname}!')

                # Hello Ada Byron!
            

What are f-strings?

Python 3.6 added "f-strings" which provide concise and convenient way to embed Python expressions inside string literals.

                f"some text {expression} more text"
            
The letter "f" is used as a prefix before the opening quotation mark of the string literal. Inside string literal we can use {} (curly braces) to embed any Python expression.
Example:

                # single line f-string:
                x = 1
                y = 2
                print(f'x + y = {x+y}')

                #x + y = 3

                # multiline f-strings
                print(f"""
                x=1
                y=2
                x+y = {x+y}
                """)

                #x=1
                #y=2
                #x+y = 3

            
More on f-strings:
Formatted String Literals @python tutorial

Formatting f-strings

The f-strings in Python allow for various format specifiers to control how the values are displayed.
Examples:

                # ------------------- Precision for Floating Point Numbers ------------------- #
                PI = 3.14159265

                # rounded to 2 decimal places:
                print(f"{PI:.2f}")
                # 3.14

                # ---------------------- Comma as a thousands separator ---------------------- #
                budget = 1234567890
                print(f'budget={budget:,}')
                # budget=1,234,567,890

                # ---------------------- Format a number as a percentage --------------------- #
                accuracy = 0.95678
                print(f"Accuracy: {accuracy:.2%}")

                # Accuracy: 95.68%
            
Reference: Format Specification Mini-Language

Formatting f-strings - more examples


            <!-- --------------------------- Width and Align --------------------------- -->
            x = 123

            # Right-align x within a 10-character wide field:
            print(f"--->{x:>10}<---")
            # --->       123<---

            # Center-align x within a 10-character wide field:
            print(f"--->{x:^10}<---")
            # --->   123    <---

            # Center-align x within a 10-character wide field, padding with '*':
            print(f'--->{x:*^10}<---')
            # --->***123****<---

            # Pad an integer with zeros.
            day = 5
            print(f"Day of the month: {day:02d}")
            # Day of the month: 05


            # ---------------------------- Dynamic Formatting ---------------------------- #
            value = 12.34567
            precision = 3

            # Use variables to determine the format.
            print(f"Value: {value:.{precision}f}")
            # Value: 12.346
        

Task

Write a program which will print next output:

                |==========|==========|
                |         1|1         |
                |        23|23        |
                |       456|456       |
                |==========|==========|
            

Solution

                print(f"|{'='*10}|{'='*10}|")
                print(f"|{1:>10}|{1:<10}|")
                print(f"|{23:>10}|{23:<10}|")
                print(f"|{456:>10}|{456:<10}|")
                print(f"|{'='*10}|{'='*10}|")
            

Mastering String Formatting: str.format() and Old-Style Percent Syntax

Why to learn str.format()

Flexibility: str.format() allows for complex and dynamic formatting which isn't always possible with f-strings.
Compatibility: It works in older versions of Python where f-strings are not available.
Learning Fundamentals: It's part of Python's core formatting capabilities and helps in understanding the evolution of string formatting in Python.

"old-style" String Formatting in Python

syntax


            "format_string" % (values_tuple)
        

            >>> "%s died in %d year" % ("Ada Byron", 1852)
            'Ada Byron died in 1852 year'
        
format_string - a string with formatting placeholders in it
values_tuple - the values which will be interpolated into the respective formatting placeholders.
Reference: printf-style String Formatting @python docs

how it works?

Example - format data as table


            print("| %10s | %10s |" % ("=" * 10, "=" * 10))
            print("| %10d | %10d |" % (1,2) )
            print("| %10d | %10d |" % (34,12) )
            print("| %10d | %10d |" % (243,126) )
            print("| %10s | %10s |" % ("=" * 10, "=" * 10))
        

            | ========== | ========== |
            |          1 |          2 |
            |         34 |         12 |
            |        243 |        126 |
            | ========== | ========== |
        

Examples - more


            x = 1.2345678
            y = 123
            print("x = %d, y = %d" % (x,y))
            print("x = %02d, y = %02d" % (x,y))
            print("x = %f, y = %f" % (x, y))
            print("x = %.2f, y = %.2f" % (x, y))
        

it's the "old style of formatting" - should we use it?

Though considered "the old way" it's still widely used and is not (still) deprecated in new Python3 versions
But the preferred way of formatting strings in Python is str.format() method
Knowing how this string formatting works, will help you to grasp the "new style", discussed in next slides.

resources

Formatted Output @python-course.eu
printf-style String Formatting @python docs

format string syntax: str.format() method

Syntax


            "string_with_placeholders".format(values_to_be_substituted)
        

            >>> "{} died in {} year".format("Ada Byron", 1852)
            'Ada Byron died in 1852 year'
        
string_with_placeholders is a string containing placeholders of the form {}
values_to_be_substituted - a comma separated list of values, which will be replaced in the respective placeholders
Reference: Format String Syntax @python docs

placeholders

You can give in placeholders an explicit positional index (counting starts from 0), which allows values to be printed in desired order


                >>> "{1} died in {0} year".format("Ada Byron", 1852)
                '1852 died in Ada Byron year'
            

new style vs old style?

The format specifier syntax is similar to the old %-formatting, with the addition of the {} and with : used instead of %. For example, '%10d' can be translated to '{:10d}' and so on.



            print("| {:10s} | {:10s} |".format("=" * 10, "=" * 10))
            print("| {:10d} | {:10d} |".format(1, 2))
            print("| {:10d} | {:10d} |".format(34, 12))
            print("| {:10d} | {:10d} |".format(243, 126))
            print("| {:10s} | {:10s} |".format("=" * 10, "=" * 10))
        

Homework

Homework

The tasks are given in next gist file
You can copy it and work directly on it. Just put your code under "### Your code here".

These slides are based on

customised version of

Hakimel's reveal.js

framework