Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

python - Create a function that checks if a string can be converted or not?

I now have a working piece of code that will check if the string is a correct character now I need to check if it can be converted to a list.

This is the prompt:

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.

Code:

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()

I have the main there just so I could make sure that is_numeric(s) was working properly.

EDIT of adding s.count into a new function

def string_to_list():
is_numeric(s) == True
for char in s:
    if s.count(".") >1:
        is_numeric = False
        break
    return is_numeric(s)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...