In Python, strings or numbers can be converted to a number of strings using various inbuilt functions like str(), int(), float(), etc. Let’s see how to use each of them.
In Python, you can easily convert a string to a number and a number to a string using built-in functions. The following is an example program that shows how to convert strings to numbers and numbers to strings:
# Converting a string to a number string_num = "1234" int_num = int(string_num) # Convert string to integer float_num = float(string_num) # Convert string to float print("Integer:", int_num) print("Float:", float_num) # Converting a number to a string int_num = 1234 float_num = 12.34 string_int = str(int_num) # Convert integer to string string_float = str(float_num) # Convert float to string print("Integer:", string_int) print("Float:", string_float)
In this example, we first create a string containing a number "1234". We then convert it to an integer and a float using the int()
and float()
functions, respectively. We print the integer and float values to the console.
Next, we create integer and float numbers and convert them to strings using the str()
function. We print the string values to the console.
Note that if you try to convert a string to a number, but the string contains non-numeric characters, you will get a ValueError
. Similarly, if you try to convert a string that represents a number with a decimal point to an integer, you will get a ValueError
. Therefore, it is important to ensure that the string contains valid numeric characters before converting it to a number.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.