繁体   English   中英

有没有一种简单的方法来检测输入是否包含“%”?

[英]Is there a simple way to detect if an input contains a '%'?

我正在尝试找出一种方法来检测假设为 54% 的字符串输入并将其转换为十进制。 我可以用一个简单的 if() 语句得到要转换的百分比并将其乘以 100。我只是不知道应该将 if 语句参数设置为什么?

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)

这将 output:

0.54
0.0037
there's a value with a % sign, which cannot be converted: apple%
input = input(': ')
percent = (% in input)
if percent == True:
    #Do what you want
    print('Correct')
else:
    print('Wrong')

如果像这样,您可以使用 in line:

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, '%')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM