2 min read•june 24, 2024
Python's numeric data types and operations are crucial for performing calculations. Integers and floats behave differently in operations, with type conversion playing a key role in mixed-type expressions.
String manipulation in Python is versatile. The repetition operator allows for easy string duplication, while concatenation enables combining strings. Understanding these operations is essential for effective string handling in Python programs.
Operations involving only integers result in an integer (
5 + 3
evaluates to 8
) while integer division (//
) always returns an integer, discarding any remainder (7 // 2
evaluates to 3
)
Operations involving at least one result in a float data type (5 + 3.0
evaluates to 8.0
) and regular division (/
) always returns a float, even if the result is a whole number (6 / 2
evaluates to 3.0
)
Mixing integers and floats in an expression causes Python to implicitly convert integers to floats before performing the operation (2 * 3.14
evaluates to 6.28
)
Convert a string to an integer using the
###[int](https://www.fiveableKeyTerm:int)()_0###
function (int("42")
returns 42
) and raises a [ValueError](https://www.fiveableKeyTerm:ValueError)
if the string cannot be converted
Convert a string to a float using the [float()](https://www.fiveableKeyTerm:float())
function (float("3.14")
returns 3.14
) and raises a ValueError
if the string cannot be converted
Convert a numeric type (integer or float) to a string using the [str](https://www.fiveableKeyTerm:str)()
function (str(42)
returns "42"
and str(3.14)
returns "3.14"
)
Arithmetic operations cannot be performed directly on strings ("2" + 3
raises a [TypeError](https://www.fiveableKeyTerm:TypeError)
) so first convert the string to the appropriate numeric type
[type()](https://www.fiveableKeyTerm:type())
function to check the data type of a variable or expressionThe repetition operator (
*
) repeats a string a specified number of times using the syntax string * integer
or integer * string
("Hello" * 3
evaluates to "HelloHelloHello"
and 2 * "World"
evaluates to "WorldWorld"
)
The repetition operator creates a new string containing the original string repeated the specified number of times
The integer used with the repetition operator must be non-negative or a ValueError
is raised
The repetition operator can be combined with string concatenation (+
) to create more complex strings ("Hello" + " " + "World" * 3
evaluates to "Hello WorldWorldWorld"
)