如何在RGB转十六进制转换器中输入元组?

huangapple go评论64阅读模式
英文:

How to input a tuple in RGB to hex converter?

问题

我原本打算编写一个简单的RGB转十六进制颜色代码,但后来在处理元组输入时出现了问题。程序如下:

rgb_val = input('输入RGB值: ')
for val in rgb_val.split(','):
    rgb = tuple(val)
hex_color = '#' + ''.join([f'{channel:02x}' for channel in rgb])
print(f'将{rgb}转换为{hex_color}')

错误出现在第4行,VSCode显示:对象类型为'str',未知的格式代码'x'。

:02x用于将RGB值转换为具有2位数的十六进制,并在位数少于2位数时用零填充数字。所以:

  1. 我不明白x的问题在哪里。
  2. 有人能提出一种处理元组输入的方法,以避免上述错误吗?

有人知道如何解决这个问题吗?提前感谢。

英文:

I intended to code a simple RGB to hex color converter but then I had a problem with tuple input. The program looks like this:

rgb_val = input('Input RGB values: ')
for val in rgb_val.split(','):
    rgb = tuple(val)
hex_color = '#' + ''.join([f'{channel:02x}' for channel in rgb])
print(f'Convert {rgb} to {hex_color}

The error is in line 4 and VSCode stated: Unknown format code 'x' for object of type 'str'

:02x is used to convert the RGB values into hexadecimal with 2 figures and pad the number with zeroes if we have fewer than 2 figures. So

  1. I don't understand what the problem was with x.
  2. Can anyone suggest a way to work with tuple input so I don't run into the above error?

Does anyone know how to fix this? Thanks in advance.

答案1

得分: 1

因为 "channel" 是字符串类型,所以需要转换为整数类型。

英文:

Because "channel" is a string type.You need to transfer to integer type.

huangapple
  • 本文由 发表于 2023年7月11日 10:21:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76658361.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定