如何将字符串百分比转换为浮点数

问题描述 投票:0回答:1

我正在使用 tkinter GUI 和 yt-dlp 库,当接近制作进度条时,我遇到了将 str 钩子转换为浮点数的问题

我有这个字符串

"\x1b[0;94m  0.0%\x1b[0m"

我需要把它变成一个浮点数:

0.0

我尝试过使用

.replace
但它只能工作到 17.7,然后我会收到如下错误:

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

如何解决这个“问题”?

python python-3.x type-conversion yt-dlp
1个回答
0
投票

假设模式始终相同,这可能是更好的方法。

import re

input_string = "\x1b[0;94m  17.7%\x1b[0m"
match = re.search(r'\b\d+\.\d+\b', input_string)
result = float(match.group())
print(result)

输出:

17.7
© www.soinside.com 2019 - 2024. All rights reserved.