我得到了一個包含4個變量的元組列表,這些元組將被打印在一行中,我希望用戶指定這些打印格式。用戶自定義格式的輸入.format()
這是我到目前爲止的代碼:
mylist = [
("Monday", "13", "November", "2017"),
("Tuesday", "14", "November", "2017"),
("Wednesday", "15", "November", "2017")]
# Note: The real list have a thousand of items, not just 3.
custom_format = self.GUI_field_where_user_types.get_text()
for item in mylist:
weekday = item[0]
daynumber = item[1]
month = item[2]
year = item[3]
print(eval(custom_format))
# Example custom_format: '"{0}, {1} of {2} from year {3}".format(weekday, daynumber, month, year)'
做檢查,我只是想與上面的輸入,它顯然作品,但我不想使用eval,因爲它顯然太危險了。所以我的問題是:如何讓用戶以一種安全的方式定義格式?
注:用戶應該能夠在.format()方法"{0}, {1} of {2} from year {3}"
之前只能編輯字符串,阻止訪問任何蟒蛇命令,但讓他只能使用變量,他想要的,並不總是4其中。一些實例中可能是:
- {0},{1}的{2}
- {3},{1}在一個月{2}
- {0},{1}的{2 }從今年{3}
- {1}任何{2} - {3}
對不起,我有點困惑。你輸入的是什麼?這:來自年份{3}「'{2}的{」{0},{1}? –