简体   繁体   English

在python中以字符串格式将十六进制剥离为一位数字

[英]strip hex to a single digit in string formating in python

I'm trying to convert RGB values to short hex format, I have the long version: 我正在尝试将RGB值转换为短十六进制格式,我使用的是长版本:

'#{:02x}{:02x}{:02x}'.format(r, g , b)

is it possible to get #fff instead of #ffffff without formatting the values one by one to take the first digits? 是否有可能获得#fff而不是#ffffff而不将值一一格式化为第一个数字?

Edit: my code doesn't require much accuracy in colors so it accepts a shortened version of color hex code that each color is represented by a single digit and the second digit is omitted. 编辑:我的代码对颜色的准确性要求不高,因此它接受彩色十六进制代码的简化版本,每种颜色用一位数字表示,第二位数字省略。

any value from 0 to 15 is considered 0 从0到15的任何值都被视为0

any value from 16 to 31 is considered 1 从16到31的任何值都被视为1

and so on... 等等...

so you have this code to output a rgb value on 24 bits 所以你有这段代码可以输出24位的rgb值

print('#{:02x}{:02x}{:02x}'.format(r, g , b))

if you want to output a rgb value on 12 bits only when the value can be shortened 如果仅在可以缩短该值的情况下要在12位上输出rgb值

if (r % 17 == 0 and g % 17 == 0 and b % 17 == 0):
     print('#{:01x}{:01x}{:01x}'.format(r/17, g/17, b/17))
else:
     print('#{:02x}{:02x}{:02x}'.format(r, g , b))

if you encode a mono chromatic color in 8 bits you have 256 values between 0 and 255 , so you have 255 intervals . 如果以8位编码单色,则0到255之间将有256个值,因此间隔为255个。

if you encode a mono chromatic color in 4 bits you have 16 values between 0 and 15 , so you have 15 intervals . 如果用4位编码单色,则0至15之间有16个值,因此有15个间隔。

so 255 / 15 => 17 所以255/15 => 17

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM