Reputation: 59
I'm trying to format some data for performing an analysis. I'm trying to remove '*'
from all strings that start with one. Here's a snippet of the 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']]
This should be simple, but nothing I've tried works. For example:
for lst in testList:
for item in lst:
item.replace('*', '')
just gives me back the same strings. I've also tried inserting an if statement and indexing the characters in the strings. I know I can access the strings. For example if I say if item[0] == '*': print item
it prints the correct items.
Upvotes: 4
Views: 11673
Reputation: 118
In your code you were replacing the *
in the dummy variable only and not effecting the list entry. Using lstrip
will only take the *
from the left had side of the string.
for x in xrange(len(testList)):
testList[x] = testList[x].lstrip('*')
Upvotes: 0
Reputation: 624
y = []
for lst in testList:
for a in lst:
z = a.replace('*','')
y.append(z)
testList = []
testList.append(y)
print testList
Upvotes: 0
Reputation: 49318
You'll have to either create a new list
(demonstrated below) or access the indices of the old one.
new_list = [[item.replace('*','') if item[0]=='*' else item for item in l] for l in old_list]
Upvotes: 0
Reputation: 20015
You can try using enumerate in order to have access to list element's index when the time comes and you need to change it:
for lst in testList:
for i, item in enumerate(lst):
if item.startswith('*'):
lst[i] = item[1:] # Or lst[i] = item.replace('*', '') for more
Upvotes: 2
Reputation: 90899
string
s are immutable , and as such item.replace('*','')
returns back the string with the replaced characters, it does not replace them inplace (it cannot , since string
s are immutable) . you can enumerate over your lists, and then assign the returned string back to the list -
Example -
for lst in testList:
for j, item in enumerate(lst):
lst[j] = item.replace('*', '')
You can also do this easily with a list comprehension -
testList = [[item.replace('*', '') for item in lst] for lst in testList]
Upvotes: 9