Algorithm


1. Start
2. Input a string from the user
3. Initialize a variable to store the result (parsed value)
4. Initialize a variable to track the type of parsing (int or float)
5. Iterate through each character in the input string:
   a. Check if the character is a digit or a decimal point
   b. If it is a digit, append it to a temporary string
   c. If it is a decimal point and the parsing type is not yet determined:
      i. Set the parsing type to float
      ii. Append the decimal point to the temporary string
   d. If the character is not a digit or a decimal point:
      i. Break the loop
6. Check the parsing type:
   a. If it is int, convert the temporary string to an integer
   b. If it is float, convert the temporary string to a float
7. Output the parsed value
8. End

Code Examples

#1 Code Example- Python Programing Parse string into integer

Code - Python Programming

balance_str = "1500"
balance_int = int(balance_str)

# print the type
print(type(balance_int))

# print the value
print(balance_int)
Copy The Code & Try With Live Editor

Output

x
+
cmd

1500

#2 Code Example- Python Programing Parse string into float

Code - Python Programming

balance_str = "1500.4"
balance_float = float(balance_str)

# print the type
print(type(balance_float))

# print the value
print(balance_float)
Copy The Code & Try With Live Editor

Output

x
+
cmd

1500.4

#3 Code Exaample- Python Programing A string float numeral into integer

Code - Python Programming

balance_str = "1500.34"
balance_int = int(float(balance_str))

# print the type
print(type(balance_int))

# print the value
print(balance_int)
Copy The Code & Try With Live Editor

Output

x
+
cmd

1500
Advertisements

Demonstration


Python Programing Example to Parse a String to a Float or Int-DevsEnv