Removing a character from a string in a list of lists
I am trying to format some data for analysis purposes. I am trying to remove '*'
from all lines that start with one. Here is a piece of data:
[['Version', 'age', 'language', 'Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6', 'Q7', 'Q8', 'Q9', 'Q10', 'Q11', 'Q12', 'Q13', 'Q14', 'Q15', 'Q16', 'Q17', 'Q18', 'Q19', 'Q20', 'Q21', 'Q22', 'Q23', 'Q24', 'Q25', 'Q26', 'Q27', 'Q28', 'Q29', 'Q30', 'Q31', 'Q32', 'Q33', 'Q34', 'Q35', 'Q36', 'Q37', 'Q38', 'Q39', 'Q40', 'Q41', 'Q42', 'Q43', 'Q44', 'Q45'], ['1', '18 to 40', 'English', '*distort', '*transfer', '*retain', 'constrict', '*secure', '*excite', '*cancel', '*hinder', '*overstate', 'channel', '*diminish', '*abolish', '*comprehend', '*tolerate', '*conduct', '*destroy', '*foster', 'direct', '*challenge', 'forego', '*cause', '*reduce', 'interrupt', '*enhance', '*misapply', '*exhaust', '*extinguish', '*assimilate', 'believe', 'harmonize', '*demolish', 'affirm', 'trouble', 'discuss', '*force', 'divide', '*remove', '*release', 'highlight', 'reinforce', 'stifle', '*compromise', '*experience', 'evaluate', 'replenish']]
It should be easy, but I haven't tried anything. For example:
for lst in testList:
for item in lst:
item.replace('*', '')
just returns the same lines to me. I have also tried inserting an if statement and indexing characters in strings. I know I can access the strings. For example, if I say if item[0] == '*': print item
, it prints the correct items.
source to share
string
are immutable and as such item.replace('*','')
returns a string with replaced characters, it does not replace them inplace (it cannot, since it is string
immutable). you can enumerate your lists and then put the returned string back into a list -
Example -
for lst in testList:
for j, item in enumerate(lst):
lst[j] = item.replace('*', '')
You can also easily deal with list comprehension -
testList = [[item.replace('*', '') for item in lst] for lst in testList]
source to share