0

Write a program, input a string , and put all the numeric strings in the string (except for the tail punctuation, it can be an integer or a float, for example, '100times', N0; '56.78.23' in the sentence, No; '45.78.' at the end of the sentence, Yes; or a single number) is converted to a floating point number and output. If there is no numeric string, output:‘Not Found!’ . The following punctuation marks may be included in the string: ",", ".", "", "?", and "!", punctuation does not appear consecutively.

Example:

string = " one 5.67 two 56.78.23 three 34 four 45.78. "

Result:

['5.67','45.78','34']
4
  • 1
    Can you share some of the code you've written and what's not working? Commented Oct 25, 2019 at 15:09
  • Use a regexp to find all the numeric strings with re.findall(). Commented Oct 25, 2019 at 15:11
  • The problem description says that you're supposed to convert them to floating point numbers. Why does your desired result have strings in it? Commented Oct 25, 2019 at 15:12
  • Are you trying to find floats or numbers? Cause 34 is not a float? Commented Oct 25, 2019 at 15:34

1 Answer 1

1

The way I'd do this is splitting the string, and trying to cast to float in a try/except clause:

def find_floats(string):
    for i in string.rstrip('. ').split():
        try:
            float(i)
            yield i
        except ValueError:
            pass

list(find_floats(string))
# ['5.67', '34', '45.78.']
Sign up to request clarification or add additional context in comments.

6 Comments

Won't float(2) turn the int 2 into 2.0?
No, it is not being assigned anywhere... @daudnadeem
no I mean if I open up a python shell, and type float("string") I get a ValueError. However both float(1) and float(1.0) return 1.0
Yes, so? OP is looking for numeric values @daudnadeem
yes, I noticed that. However the question is misleading since it states "float in sting" and not "numbers in string"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.