创建一个检查字符串是否可以转换的函数?

2024-04-27 02:50:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在有一个工作的代码,将检查字符串是否是一个正确的字符,现在我需要检查它是否可以转换成一个列表。你知道吗

提示如下:

string_to_list() - This function takes a string parameter and returns the list of the numbers in the string. First it should call the is_numeric() function to check that the string has no bad characters (e.g. letters). If there are any bad characters, it should return the empty list. If there are no bad characters it should try to build the list out of teh data in the string. For this it should look at every substring between two consecutive commas. If there is no dot in that substring, then the substring should be converted to an integer. If there is exactly one dot (no more, no less) it should be converted into a float. If any of the substrings between two consecutive commas can not be converted to an int or a float (e.g. "4.5.8" as it has too many dots), the function should still return the empty list. Hint: the split() method may be useful for this task.

代码:

s = input("Enter a set of numbers (integers or floats) separated by comma:")
L = []

def is_numeric(s):
    is_digit = True

    for char in s:
        if not char.isdigit() and char not in [" ", ".", ","]:
            is_digit = False
            break

    return is_digit
"""
Above checks to see if all the characters in string are good if they are the function is true
"""
def main():  
    if is_numeric(s) == True:
        print(s)
    else:
        print(L)

main()

我在那里有一个主要的,只是为了我可以确保是\u数字是正常工作。你知道吗

向新函数中添加s.count的编辑

def string_to_list():
is_numeric(s) == True
for char in s:
    if s.count(".") >1:
        is_numeric = False
        break
    return is_numeric(s)

Tags: ofthetonoinstringifis