可能有很多原因: 1. rgb在這種情況下應該是元組有3個值。因此,元組形式的(255,255,255)需要在這裏傳遞,而不是(255,255,255,1) 2. rgb必須是一個元組,如果它是字符串,這將不起作用。
嘗試在Python解釋器使用以下命令
"#%02x%02x%02x" % (255, 255, 255)
它會給預期的結果 「#FFFFFF」
如果我們運行下面的
"#%02x%02x%02x" % (255, 255, 255,1)
它會說不是所有的參數在字符串格式化期間轉換。
但是,從問題中顯示的堆棧跟蹤看起來像傳遞'(255,255,255,1)'作爲單個字符串,顯然不能解析爲它。 因此,確保在將它傳遞給格式化程序之前,將「(255,255,255,1)」字符串轉換爲元組(255,255,255)。你可以在字符串上使用split函數來解析它,然後從分割的值中創建一個元組。請記住從分割的字符串中刪除括號。
e.g
DEF rgb_to_hex(RGB): #for例如,如果RGB = 「(255,255,255,1)」
new_string = rgb[1:-4] # remove starting brace and , 1) from last
# new_strings will be "255, 255, 255"
string_fractions = input_string.split(",")
# string fractions will be ['255', ' 255', ' 255']
# now notice it is list of strings and we need a tuple of ints
int_tuples = tuple(map(int, input_string.split(",")))
# int_tuples will be (255, 255, 255)
return '#%02x%02x%02x' % int_tuples
請張貼[MCVE]。 –
你應該轉換 – cutzero