Python|打印不带引号的列表的方法
每当我们在Python中打印 list 时,我们通常使用 str(list),因为我们在输出列表中有单引号。假设问题是否需要打印不带引号的解决方案。让我们看看一些打印不带引号的列表的方法。
方法 #1:使用map()
# Python code to demonstrate
# printing list in a proper way
# Initialising list
ini_list = ['a', 'b', 'c', 'd']
# Printing initial list with str
print ("List with str", str(ini_list))
# Printing list using map
print ("List in proper method", '[%s]' % ', '.join(map(str, ini_list)))
输出:
List with str ['a', 'b', 'c', 'd']
List in proper method [a, b, c, d]
方法 #2:使用sep
方法
# Python code to demonstrate
# printing list in proper way
# Initialising list
ini_list = ['a', 'b', 'c', 'd']
# Printing initial list with str
print ("List with str", str(ini_list))
# Printing list using sep Method
print (*ini_list, sep =', ')
输出:
List with str ['a', 'b', 'c', 'd']
a, b, c, d
方法 #3:使用 .format()
# Python code to demonstrate
# printing list in proper way
# Initialising list
ini_list = ['a', 'b', 'c', 'd']
# Printing initial list with str
print ("List with str", str(ini_list))
# Printing list using .format()
print ("Printing list without quotes", ("[{0}]".format(
', '.join(map(str, ini_list)))))
输出:
List with str ['a', 'b', 'c', 'd']
Printing list without quotes [a, b, c, d]
方法#4:使用translate
方法
# Python code to demonstrate
# printing list in proper way
# Initialising list
ini_list = ['a', 'b', 'c', 'd']
# Printing initial list with str
print ("List with str", str(ini_list))
translation = {39: None}
# Printing list using translate Method
print ("Printing list without quotes",
str(ini_list).translate(translation))
输出:
List with str ['a', 'b', 'c', 'd']
Printing list without quotes [a, b, c, d]