Home > OS >  Python: How to prevent special characters in input
Python: How to prevent special characters in input

Time:11-03

My problem is when I enter a number in the input field, it becomes number with special character. I don't know why it's adding extra characters to input. You can see the example. I entered just 5.2 and it became '5.2&

"""
length of rectangle = a
width of rectangle = b
calculate the area and perimeter of the rectangle
"""

a = 6
b = float(input("width: "))

area = a*b
perimeter = (2*a)   (2*b)

print("area: "   str(area)   " perimeter: "   str(perimeter))
File "c:\Users\HP\OneDrive - Karabuk University\Belgeler\Downloads\first.py", line 8, in <module>
b = float(input("width: "))
ValueError: could not convert string to float: '5.2&

Could you please help me?

CodePudding user response:

For me It's working fine...See my output..

Note: It throws error at last line in your code because you can't concatenate a str with an int.

So, you need to convert int to str before concatenating your variables

a = 6
b = float(input("width: "))
print(b)

area = a*b
perimeter = (2*a)   (2*b)

print("area: "   str(area)   " perimeter: "   str(perimeter))

#output

width: 5.2
5.2
area: 31.200000000000003 perimeter: 22.4

Alternate solution 2

Idk why it's adding extra chars to your user input...Anyway you can filter user input once entered as follows.

import re
a = 6
b = (input("width: "))
b=str(b)
b=re.sub("[^0-9^.]", "", b)

b=float(b)
print(b)

area = a*b
perimeter = (2*a)   (2*b)

print("area: "   str(area)   " perimeter: "   str(perimeter))

output #

width: 5.2b
5.2
area: 31.200000000000003 perimeter: 22.4

CodePudding user response:

"""
length of rectangle = a
width of rectangle = b
calculate the area and perimeter of the rectangle
"""

"""
We cannot replicate this error.
b = float(input("width: "))
ValueError: could not convert string to float: '5.2&

Debug by breaking down the code to see which function is the source of the 
error.
"""
a = 6
# b = float(input("width: "))
s = input("width: ")
print("s= "   s)
b = float (s)
area = a*b
perimeter = (2*a)   (2*b)

print("area: "   str(area)   " perimeter: "   str(perimeter))

Output

width: 5.2
s= 5.2
area: 31.200000000000003 perimeter: 22.4
  • Related