I have a list : lst = [('asd'),('fgb'),('tre'),...]
like this . I want to remove "(" and ")" characters . The result must be : ['asd','fgb','tre',...]
Asked
Active
Viewed 74 times
-6

Cahit Yıldırım
- 499
- 1
- 10
- 26
-
3The result already is `['asd','fgb','tre'...` unless you have a string and not actually a list – Padraic Cunningham Dec 26 '15 at 00:42
2 Answers
2
Note that ()
around a string is just a syntactic sugar in python, which has no literal meaning.
Example:
>>> 'asd' == ('asd')
True
If you really want to fix this, one way would be:
>>> x = [('asd'),('fgb'),('tre')]
>>> x
['asd', 'fgb', 'tre']
>>> xx = [i for i in x]
>>> xx
['asd', 'fgb', 'tre']
But it does not really make any difference in the way python would parse the list

karthikr
- 97,368
- 26
- 197
- 188
-
Or just `x`; list's repr method shouldn't know about the parenthesis. – Colonel Thirty Two Dec 26 '15 at 00:38
-
True, but i have a feeling this might not actually be a string generated by the interpreter. . – karthikr Dec 26 '15 at 00:41
-
-
1
If your list looks exactly like you posted it, then the parentheses do nothing, so there are none to remove:
>>> [('asd'),('fgb'),('tre')]
['asd', 'fgb', 'tre']
I am assuming that the parentheses are actually part of your strings (you probably misplaced the quotation marks) and that you only want the ones at the start and the beginning of a string in your list removed:
>>> lst = ['(asd)', '(fgb)', '(tre)']
>>> [x[1:-1] for x in lst]
['asd', 'fgb', 'tre']
Otherwise, if you want to remove all parentheses you can use re
:
>>> [re.sub('\)|\(', '', s) for s in lst]
['asd', 'fgb', 'tre']
or chain str.replace
>>> [s.replace('(', '').replace(')', '') for s in lst]
['asd', 'fgb', 'tre']

timgeb
- 76,762
- 20
- 123
- 145