1. Inputs, Output, Strings and Help

Basic Operations with Python

Let's learn from examples:

>>> print(5,6,7)
5 6 7
>>> print('LOVE', 30, 82.2)
LOVE 30 82.2
>>> print('LOVE', 30, 82.2, sep=',')
'LOVE', 30, 82.2
>>> print('LOVE', 30, 82.2, sep=',', end='!!\n')
'LOVE', 30, 82.2!!

Let's play with the Input function a little bit. input() -> str

>>> beautiful_number = input()
6
>>> type(beautiful_number)
<class 'str'>
>>> beautiful_number = int(input())
6
>>> type(beautiful_number)
<class 'int'>
>>> for i in "python":
... print(i)
...
p
y
t
h
o
n
>>> for i in "python":
... print(i, end=":")
...
p:y:t:h:o:n:

Strings

  • Strings in Python are immutable.

>>> a = "hello"
>>> a + " dear"
'hello dear'
>>> a
'hello'

String Slicing

>>> a.upper()
'HELLO'
>>> len(a)
5
>>> a[0]
'h'
>>> a[-1]
'o'
>>> a[::] # String slicing
'hello'
>>> a[::-1]
'olleh'
>>> a.find('l')
2
>>> a[1:3]
'el'
>>> a[1:]
'ello'

String Formatting

Example 1: Simple example of string format

>>> name = "Bablu Kumar"
>>> number = len(name) * 3
>>> print("Hello {}, your lucky number is {}.".format(name, number))
Hello Bablu Kumar, your lucky number is 33.
>>> print("Hello {n}, your lucky number is {num}".format(n=name, num=len(name) * 3))
Hello Bablu Kumar, your lucky number is 33

Example 2: Showing only two numbers after the decimal.

.2f this means we're going to format a float number and that there should be two digits after the decimal dot.

>>> price = 7.5
>>> with_tax = price * 1.09
>>> print(price, with_tax)
7.5 8.175
>>>
>>> print("Base Price: ${:.2f}, With Tax: ${:.2f}".format(price, with_tax))
Base Price: $7.50, With Tax: $8.18

Example 3:

  • :>3: we're using the greater than operator to align text to the right so that the output is neatly aligned.

    • In the first expression we're saying we want the numbers to be aligned to the right for a total of three spaces.

  • :>6.2f: In the second expression we're saying we want the number to always have exactly two decimal places and we want to align it to the right at six spaces.

>>> def to_celsius(x):
return (x-32)*5/9
>>> for x in range(0, 101, 10):
print("{:>3} F | {:>6.2f} C".format(x, to_celsius(x)))
0 F | -17.78 C
10 F | -12.22 C
20 F | -6.67 C
30 F | -1.11 C
40 F | 4.44 C
50 F | 10.00 C
60 F | 15.56 C
70 F | 21.11 C
80 F | 26.67 C
90 F | 32.22 C
100 F | 37.78 C

Notice the difference between :>3 and :<3 in the string formatting.

>>> def to_celsius(x):
return (x-32)*5/9
>>> for x in range(0, 101, 10):
print("{:<3} F | {:>4.2f} C".format(x, to_celsius(x)))
0 F | -17.78 C
10 F | -12.22 C
20 F | -6.67 C
30 F | -1.11 C
40 F | 4.44 C
50 F | 10.00 C
60 F | 15.56 C
70 F | 21.11 C
80 F | 26.67 C
90 F | 32.22 C
100 F | 37.78 C

F-String

### Example 1
>>> name = "BK"
>>> age = 34
>>> print(f"My name is {name}. I am {age} years old.")
My name is BK. I am 34 years old.
### Example 2
>>> print(f"The \"comedian\" is {name}, aged {age}.")
'The "comedian" is BK, aged 34.'
### Example 3
>>> print(f"The \"comedian\" is {name}, aged {age:.2f}")
The "comedian" is BK, aged 34.00
### Example 4
>>> comedian = {'name': 'Eric Idle', 'age': 74}
>>> print(f"My name is {comedian['name']}. My age is {comedian['age']}")
My name is Eric Idle. My age is 74

Cheat Sheet

Expr

Meaning

Example

{:d}

integer value

'{:d}'.format(10.5) → '10'

{:.2f}

floating point with that many decimals

'{:.2f}'.format(0.5) → '0.50'

{:.2s}

string with that many characters

'{:.2s}'.format('Python') → 'Py'

{:<6s}

string aligned to the left that many spaces

'{:<6s}'.format('Py') → 'Py '

{:>6s}

string aligned to the right that many spaces

'{:>6s}'.format('Py') → ' Py'

{:^6s}

string centered in that many spaces

'{:^6s}'.format('Py') → ' Py '

String Methods

  • s.lower(), s.upper() -- returns the lowercase or uppercase version of the string

  • s.strip() -- returns a string with whitespace removed from the start and end

  • s.isalpha()/s.isdigit()/s.isspace()... -- tests if all the string chars are in the various character classes

  • s.startswith('other'), s.endswith('other') -- tests if the string starts or ends with the given other string

  • s.find('other') -- searches for the given other string (not a regular expression) within s, and returns the first index where it begins or -1 if not found

  • s.replace('old', 'new') -- returns a string where all occurrences of 'old' have been replaced by 'new'

  • s.split('delim') -- returns a list of substrings separated by the given delimiter. The delimiter is not a regular expression, it's just text. 'aaa,bbb,ccc'.split(',') -> ['aaa', 'bbb', 'ccc']. As a convenient special case s.split() (with no arguments) splits on all whitespace chars.

  • s.join(list) -- opposite of split(), joins the elements in the given list together using the string as the delimiter. e.g. '---'.join(['aaa', 'bbb', 'ccc']) -> aaa---bbb---ccc

Help for Python

  • dir() and help()