Python: How to prevent special characters in input

Question:

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:UsersHPOneDrive - Karabuk UniversityBelgelerDownloadsfirst.py", line 8, in <module>
b = float(input("width: "))
ValueError: could not convert string to float: '5.2&

Could you please help me?

Asked By: gismgism

||

Answers:

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
Answered By: Bhargav
"""
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
Answered By: Carl_M
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.