我正在尝试找出一种方法来检测假设为54%的字符串输入并将其转换为十进制。我可以使用简单的if()语句并将其乘以100来获得要转换的百分比。我只是不知道应该将if语句参数设置为什么?
答案 0 :(得分:2)
lst = ['54%', '54', '0.37%', 'apple%']
# Go through the list
for i in lst:
# Check whether there's a percent sign
if '%' in i:
# Try whether only taking away the % sign is enough for it to be able to be divideable
try:
# Take out that % sign
percent = float(i.replace('%', ''))
decimal = percent / 100
print(decimal)
# If taking the % sign away is not enough, do the following stuff
except:
# Create an empty list which we will append to later and set a variable to 0
lstnumbers = []
errors = 0
# Go through every character of the item
for numbers in i:
# Check whether it can be changed to an integer and append it to a list
try:
number = int(numbers)
lstnumbers.append(number)
# Increase the variable by 1 if there's a charachter that can't be converted to an integer
except:
errors += 1
# If there's something with a % that can't be converted to an integer, print that
if errors > 0:
print("there's a value with a % sign, which cannot be converted:", i)
# If there were some integers in the item, do something
if len(lstnumbers) > 0:
# Replace the first 0 as it the input could also be 0.46 for example and 046 would be no number we'd be interested in
lstnumbersnew = ['' if lstnumbers[0] == '0' else number for number in lstnumbers]
# Bring the items from the list together so we have string
finalnumber = ''.join(str(lstnumbersnew))
# Make that string an integer and divide it
finalintegers = int(float(finalnumber)) / 100
# Print it or do whatever you want to do with it
print(finalintegers)
这将输出:
0.54
0.0037
there's a value with a % sign, which cannot be converted: apple%
答案 1 :(得分:0)
input = input(': ')
percent = (% in input)
if percent == True:
#Do what you want
print('Correct')
else:
print('Wrong')
答案 2 :(得分:0)
如果这样的话,您可以使用一行代码:
def detectInput(inp, charToDetect): # inp = the user input
# if % in inp then convert else do nothing
print(((int(inp.replace(charToDetect, '')))/100) if (charToDetect in inp) else "")
x = "54%"
detectInput(x, '%')