How to convert a string to a number

Before anything else, you might ask yourself why would anyone want to do this? Well, sometimes we get data from external sources that comes as a string instead of a number. For example, let’s say you have a CSV file with sales figures for the past year and one column is labeled “Total Sales” but it actually contains strings like “$123,456”. You can’t do any calculations on this data unless you convert those strings to actual numbers!

So how do we do that? It’s pretty simple, really. We use the built-in `int()` or `float()` functions in Python. Let me show you an example:

# This script converts a string containing a dollar amount to an integer value, removing any commas in the process.

# First, we define a variable "string_num" and assign it a string value of "$123,456"
string_num = "$123,456"

# Next, we use the replace() function to remove the commas from the string and assign the result to a new variable "number_num"
# The replace() function takes two arguments - the first is the character to be replaced (in this case, a comma), and the second is the character to replace it with (in this case, an empty string)
# This effectively removes all commas from the string, leaving only the numbers
number_num = int(string_num.replace(",", ""))

# We use the int() function to convert the string to an integer value
# This allows us to perform calculations on the number, as opposed to a string which cannot be used in calculations
# We also use the print() function to output the type of the variable "number_num"
# This allows us to confirm that the conversion was successful and the variable is now an integer
print(type(number_num)) # output: <class 'int'>

In this example, we first create a variable called `string_num` and assign it a value of “$123,456”. Then we use the `replace()` method to remove any commas from that string. Finally, we pass the resulting string (without commas) into the `int()` function which converts it to an integer.

If you have strings with decimal points instead of commas, just replace the comma with a period and use the `float()` function instead:

# Define a string variable containing a number with a decimal point
string_num = "123.456"

# Use the `float()` function to convert the string into a float data type
number_num = float(string_num)

# Print the data type of the converted number
print(type(number_num))  # output: <class 'float'>

# Note: No need to remove decimals since they're already in place, so we can directly use the `float()` function instead of `int()`

And that’s it! You can now perform calculations on your converted numbers.

SICORPS