Python – 删除元组元素之间的空格
有时,在使用元组时,我们可能会遇到需要打印元组的问题,逗号和下一个元素之间没有空格,按照惯例,这是存在的。这个问题可以在白天和学校编程中使用。让我们讨论可以执行此任务的某些方式。
Input : test_tuple = (7, 6, 8)
Output : (7, 6, 8)
Input : test_tuple = (6, 8)
Output : (6, 8)
方法 #1:使用 str() + replace()
上述功能的组合可以用来解决这个问题。在此,我们通过替换为空白空间来执行移除额外空间的任务。
Python3
# Python3 code to demonstrate working of
# Remove space between tuple elements
# Using replace() + str()
# initializing tuples
test_tuple = (4, 5, 7, 6, 8)
# printing original tuple
print("The original tuple : " + str(test_tuple))
# Remove space between tuple elements
# Using replace() + str()
res = str(test_tuple).replace(' ', '')
# printing result
print("The tuple after space removal : " + str(res))
Python3
# Python3 code to demonstrate working of
# Remove space between tuple elements
# Using join() + map()
# initializing tuples
test_tuple = (4, 5, 7, 6, 8)
# printing original tuple
print("The original tuple : " + str(test_tuple))
# Remove space between tuple elements
# Using join() + map()
res = "(" + ", ".join(map(str, test_tuple)) + ")"
# printing result
print("The tuple after space removal : " + str(res))
输出 :
The original tuple : (4, 5, 7, 6, 8)
The tuple after space removal : (4, 5, 7, 6, 8)
方法 #2:使用 join() + map()
解决这个问题的另一种方法。在此,我们通过使用 join() 对每个元素进行外部连接来执行删除空间的任务,并使用 map() 将字符串转换的逻辑扩展到每个元素。
Python3
# Python3 code to demonstrate working of
# Remove space between tuple elements
# Using join() + map()
# initializing tuples
test_tuple = (4, 5, 7, 6, 8)
# printing original tuple
print("The original tuple : " + str(test_tuple))
# Remove space between tuple elements
# Using join() + map()
res = "(" + ", ".join(map(str, test_tuple)) + ")"
# printing result
print("The tuple after space removal : " + str(res))
输出 :
The original tuple : (4, 5, 7, 6, 8)
The tuple after space removal : (4, 5, 7, 6, 8)