I am given a list of tuples, and I am trying to remove the white spaces after the strings in each list. It can result in either a list of lists, or a list of tuples as the original structure.
lst = [('4', 'tim ', 'dba', '7'), ('5', 'joe ', 'sysadmin', '8')]
lists = [list(x) for x in lst]
for x lists:
for y in x:
y = str(y)
y = "".join(y.split())
print(lst)
CodePudding user response:
this list comprehension will strip
the strings of leading and trailing whitespace:
[tuple(s.strip() for s in t) for t in lst]
# [('4', 'tim', 'dba', '7'), ('5', 'joe', 'sysadmin', '8')]
CodePudding user response:
The problem is with the for
loop itself. range
function returns an iterable object that contains the number from the first argument to the second argument with a default step of 1.
Also, note that tuples are immutable, meaning that they can not change after the first initialization.
I have modified your own script and came up with what follows:
lst = [('4', 'tim ', 'dba', '7'), ('5', 'joe ', 'sysadmin', '8')]
lists = [list(x) for x in lst]
for index1, x in enumerate(lst):
innerLst = list(x)
for index2, y in enumerate(x):
innerLst[index2] = y.replace(" ", "")
lst[index1] = tuple(innerLst)
print(last)
Output
[('4', 'tim', 'dba', '7'), ('5', 'joe', 'sysadmin', '8')]