-6

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

Cahit Yıldırım
  • 499
  • 1
  • 10
  • 26

2 Answers2

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
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