欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > Python-59:RGB色值转换为整数值

Python-59:RGB色值转换为整数值

2025/5/3 10:50:38 来源:https://blog.csdn.net/huangcheng86/article/details/147655443  浏览:    关键词:Python-59:RGB色值转换为整数值

问题描述

小M需要一个函数,用于将RGB颜色值转换为相应的十六进制整数值。RGB色值以字符串的形式给出,如"rgb(192, 192, 192)",需要转换为对应的整数值。

代码

import re

def solution(rgb):

    # Please write your code here

    mc = re.findall(r'\d+', rgb)

    if not mc or len(mc) != 3:

        raise ValueError('Invalid rgb')

    mc = list(map(int, mc))

    if any(d < 0 or d > 255 for d in mc):

        raise ValueError('Invalid rgb')

    # Method 1: Using bitwise operations

    result1 = (mc[0] << 16) + (mc[1] << 8) + mc[2]

    # Method 2: Using formatted string and parsing to int

    result2 = int(''.join(f'{x:02x}' for x in mc), 16)

    if result1 == result2:

        return result1

    raise ValueError

if __name__ == "__main__":

    #  You can add more test cases here

    print(solution("rgb(192, 192, 192)") == 12632256 )

    print(solution("rgb(100, 0, 252)") == 6553852)

    print(solution("rgb(33, 44, 55)") == 2174007)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词