Search code examples
pythonpython-3.xtype-conversionyt-dlp

How do i convert string percentage into float


I am using a tkinter GUI with the yt-dlp library, when approaching to make a progress bar, I get a problem to conversing the str hook into a float

I have this string "\x1b[0;94m 0.0%\x1b[0m"

that I need to turn in to a float into this:

0.0

I have tried using .replace but it only works up to 17.7, then I get errors such as:

ValueError: could not convert string to float: '\x1b[0;94m 17.7'

How can I solve this "problem"?


Solution

  • The string you provided seems to contain ANSI escape codes for color formatting. To extract the float value from this string you need to remove the ANSI escape codes and the percentage sign (%) and then convert the remaining string to a float.

    import re
    
    input_string = "\x1b[0;94m 17.7%\x1b[0m"
    
    # Remove ANSI escape codes and percentage sign
    extracted_string = re.sub(r'\x1b\[[0-9;]*m', '', input_string)
    extracted_string = re.sub(r'%', '', extracted_string)
    result = float(extracted_string)
    
    print(result)