π©βπ» { A JavaScript developer, who try to solves LeetCode problems using Python and Java )
My Python knowledge feels like a puzzle with missing piecesπ€
because Iβve learned the language primarily through code samples & solving problems.Iβm working on filling in the gaps and deepening my understanding of the language by writing TIL.
In Python, you can't connect different types directly, as Python does not perform implicit type coercion like JavaScript. There is a different Ways to Perform String Interpolation.
The closest equivalent to JavaScript template literals, with support for:
num1 = 2
num2 = 3
result = f"The sum of {num1} and {num2} is {num1 + num2}."
print(result) # Output: The sum of 2 and 3 is 5.
str.format()Uses placeholders {} replaced by arguments passed to the format() method.
name = "Bob"
age = 25
greeting = "Hello, {}! You are {} years old.".format(name, age)
print(greeting) # Output: Hello, Bob! You are 25 years old.
keyword_greeting = "Hello, {name}! You are {age} years old.".format(name="Charlie", age=40)
print(keyword_greeting) # Output: Hello, Charlie! You are 40 years old.
% OperatorAn older style resembling the syntax of C's printf.
name = "Dave"
age = 35
greeting = "Hello, %s! You are %d years old." % (name, age)
print(greeting) # Output: Hello, Dave! You are 35 years old.
The string module provides a Template class for simple substitutions.
from string import Template
name = "Eve"
age = 28
template = Template("Hello, $name! You are $age years old.")
greeting = template.substitute(name=name, age=age)
print(greeting) # Output: Hello, Eve! You are 28 years old.
List slicing allows flexible operations on lists, even supporting "out-of-bound" indexing without raising errors.
arr = [1, 2, 3]
copy_arr = arr[:]
print(copy_arr) # Output: [1, 2, 3]
arr = [1, 2, 3, 4, 5]
arr[1:4] = [9, 8, 7]
print(arr) # Output: [1, 9, 8, 7, 5]
arr = [1, 2, 3]
arr[:] = []
print(arr) # Output: []
arr = [0, 1, 2, 3, 4, 5, 6]
# Every second element
print(arr[::2]) # Output: [0, 2, 4, 6]
# Every second element, reversed
print(arr[::-2]) # Output: [6, 4, 2, 0]
# From index 1 to 7, every second element
print(arr[1:7:2]) # Output: [1, 3, 5]
# From index 6 to 0, reversed, every second element
print(arr[6:0:-2]) # Output: [6, 4, 2]
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# First row
print(matrix[0]) # Output: [1, 2, 3]
# First column
print([row[0] for row in matrix]) # Output: [1, 4, 7]
# Submatrix
print(matrix[1:3]) # Output: [[4, 5, 6], [7, 8, 9]]
arr = [1, 2, 3, 4, 5]
# Reverse and double elements
print([x * 2 for x in arr[::-1]]) # Output: [10, 8, 6, 4, 2]
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# From index -2 to end
print(a[-2:]) # Output: [8, 9]
# From start to index -3 (excluding -3)
print(a[:-3]) # Output: [1, 2, 3, 4, 5, 6]
# From index -4 to -1 (excluding -1)
print(a[-4:-1]) # Output: [6, 7, 8]
# From index -8 to -1, every second element
print(a[-8:-1:2]) # Output: [2, 4, 6, 8]