x = "Hello" print(x) # Output: Hello y = 1 print(y) # Output: 1 z = False print(z) # Output: FalseMultiple assignment: Assign multiple variables with different values in one instruction:
x, y , z = 'hello', 'python', 3 print(type(x)) # Output: <class 'str'> print(type(y)) # Output: <class 'str'> print(type(z)) # Output: <class 'int'>Multiple assignment: Assign same value to multiple variables:
x = y = z = 1Swapping variables:
x, y = 1, 2 x, y = y, x # x will have the value 2 and y will have the value 1
# this is a single-line comment x = 1 # this is an inline commentFor multi-line comments, use triple quotes (''', """):
""" this is a multi-line comment using triple double quotes """ ''' this is another multi-line comment using triple single quotes '''
i = 5 % 2 print(i) # Output: 1Using underscores for readability:
i = 1_000_000 print(i) # Output: 1000000Complex numbers:
i = 1 + 2j print(i) # Output: (1+2j)
a = "This is a valid string" # double quotes c = 'This is a valid string' # single quotes b = "This is a 'valid' string" # mixed quotes d = 'This is a "valid" string' # escaped quotes
a = """This is a valid multi-line string"""
print('hello python'.title()) # Output: Hello PythonThe upper() function changes a string to all uppercase:
print('hello python'.upper()) # Output: HELLO PYTHONThe lower() function changes a string to all lowercase:
print('HELLO PYTHON'.lower()) # Output: hello python
x='hello' y='python' z=f'message: {x} {y.title()}: {2.53 * 2.98:.1f}' w=f"message: {x} {y.title()}: {2.53 * 2.98:.1f}" print(z) # Output: message: hello Python: 7.5 print(w) # Output: message: hello Python: 7.5You can also use the format() method:
print("hello {}: {}".format("python", 7.5)) # Output: hello python: 7.5
print("hello\n\n\t\tpython")Output:
hello python
x = ' hello python 'Use strip() function to remove whitespace from the beginning (left) and the end (right) of a string:
print(f'"{x.strip()}"') # Output: "hello python"Use lstrip() function to remove whitespace from the beginning (left) of a string:
print(f'"{x.lstrip()}"') # Output: "hello python "Use rstrip() function to remove whitespace from the end (right) of a string:
print(f'"{x.rstrip()}"') # Output: " hello python"
x = "hello.py" print(f'"{x.removeprefix("hello")}"') # Output: ".py" print(f'"{x.removesuffix(".py")}"') # Output: "hello"
words = 'hello python 3'.split() print(f'Number of words: {len(words)} | {words}') # Output: Number of words: 3 | ['hello', 'python', '3'] for word in words: print(f'word: {word} | length: {len(word)}')Output:
Number of words: 3 | ['hello', 'python', '3'] word: hello | length: 5 word: python | length: 6 word: 3 | length: 1
words = 'hello,python,3'.split(',') print(f'Number of words: {len(words)} | {words}') # Output: Number of words: 3 | ['hello', 'python', '3'] for word in words: print(f'word: {word} | length: {len(word)}')Output:
Number of words: 3 | ['hello', 'python', '3'] word: hello | length: 5 word: python | length: 6 word: 3 | length: 1
lines = 'hello\npython\n3'.splitlines() print(f'Number of lines: {len(lines)} | {lines}') # Output: Number of lines: 3 | ['hello', 'python', '3'] for line in lines: print(f'line: {line}')Output:
Number of lines: 3 | ['hello', 'python', '3'] line: hello line: python line: 3
x = int('1') print(type(x)) # <class 'int'> print(x) # Output: 1 y = float('1.2') print(type(y)) # <class 'float'> print(float('1.2')) # Output: 1.2Handling conversion errors:
try: print(int('a')) except ValueError: # ValueError: invalid literal for int() with base 10: 'a' print("invalid number format")Convert numbers to string:
x = str(1.2) print(type(x)) # <class 'str'> print(x) # Output: 1.2
# join print(' '.join(['hello', 'python', '3'])) # Output: hello python 3 # in (membership) print('python' in 'hello python 3') # Output: True # startswith print('hello python 3'.startswith('hello')) # Output: True # endswith print('hello python 3'.endswith('3')) # Output: True # python print('hello python 3'.find('python')) # Output: 6 (index position) # count print('hello python 3'.count('o')) # Output: 2 # replace print('hello python 3'.replace('3', '3.12.3')) # Output: hello python 3.12.3
from datetime import datetime, date, timedelta, timezone
print(f'{datetime.now()}') # Output: 2023-03-29 06:19:17.217238 print(f'{date.today()}') # Output: 2023-03-29 print(f'{datetime.now().time()}') # Output: 06:19:17.217294
print(f'{date(2023, 3, 29)}') # Output: 2023-03-29 print(f'{datetime(2023, 3, 29, 6, 19, 17)}') # Output: 2023-03-29 06:19:17
print(datetime.strptime('05/08/2023 01-16-26 PM', '%d/%m/%Y %I-%M-%S %p')) # Output: 2023-08-05 13:16:26
print(datetime.now(timezone.utc).strftime('%d/%m/%Y %I-%M-%S %p %z %Z')) # Output: 29/05/2023 03-38-45 PM +0000 UTC print(datetime.now(timezone(timedelta(hours=-5))).strftime('%d/%m/%Y %I-%M-%S %p %z %Z')) # Output: 29/05/2023 10-38-45 AM -0500 UTC-05:00 print(f"{datetime.now().year} - {datetime.now().month} - {datetime.now().day} - {datetime.now().hour} - {datetime.now().minute}") # Output: 2023 - 5 - 29 - 11 - 46
print(date.today()) # Output: 2023-05-29 print(date.today() - timedelta(days=1)) # Output: 2023-05-28 print(date.today() - timedelta(weeks=1)) # Output: 2023-05-22 print(date(2023, 3, 29) - date(2000, 3, 29)) # Output: 8400 days, 0:00:00 print(date(2023, 3, 29) < date(2000, 3, 29)) # Output: False print(min([date(2023, 3, 29), date(2000, 3, 29)])) # Output: 2000-03-29 print(max([date(2023, 3, 29), date(2000, 3, 29)])) # Output: 2023-03-29