Convert a string to integer or float
You can use the ‘int()
‘ function to convert a string to an integer in Python.
Example:
string = "123"
number = int(string)
print(number)
Output:
123
If the string cannot be converted to an integer, a ‘ValueError
‘ will be raised.
You can also use other function such as ‘float()
‘ if you want to convert string to float.
string = "123.45"
number = float(string)
print(number)
Output:
123.45
Note: The input string should only contain numeric characters and an optional leading ‘+
‘ or ‘-
‘ sign otherwise it will raise a ‘ValueError
‘.
Convert Integer to String
You can use the ‘str()
‘ function to convert an integer to a string in Python.
Example:
number = 123
string = str(number)
print(string)
Output:
123
You can also use the ‘format()
‘ method or the f-strings (formatted string literals) introduced in Python 3.6 for more flexibility and readability when formatting numbers as strings.
Example:
x = 123
print("The number is: {}".format(x))
or
x = 123
print(f"The number is: {x}")
Both will give output:
The number is "123"
Note that the ‘str()
‘ function returns a human-readable string representation of the number, while ‘format()
‘ and f-strings provide a way to format the string representation with more control over the output.