Reputation: 883
I'm new with python, given this list:
a_list=['''('string','string'),...,('string','string'), 'STRING' ''']
How can I drop the quotes, parenthesis, and leaving out 'STRING' in order to get a string like this:
string string ... string
This is what I all ready tried:
new_list = ''.join( c for c in ''.join(str(v) for v
in a_list)
if c not in ",'()")
print new_list
Upvotes: 0
Views: 52
Reputation: 52071
I know that the other answer is the perfect one, But as you wanted to learn more about string techniques rather than using the present libraries then this will also work.
Do note that this is a VERY BAD way to solve your problem.
a_list=['''('string','string'),...,('string','string'), 'STRING' ''']
new_list = []
for i in a_list:
j = i.replace("'",'')
j = j.replace('(','')
j = j.replace(')','')
j = j.replace(',',' ')
j = j.replace('STRING','')
j = j.strip()
new_list.append(j)
print new_list
It will output
'string string ... string string'
Upvotes: 1
Reputation: 10350
If your string doesn't have a literal ...
, you can use ast.literal_eval
here. That will convert your string into a tuple (whose elements are 2-tuples and strings), since it basically is the string representation of a tuple. After that, it's a simple matter of iterating over the tuple and converting it to the form you want.
>>> import ast
>>> x = '''('string','string'), ('string2','string3'), ('string','string'), 'STRING' '''
>>> y = ast.literal_eval(x); print(y)
(('string', 'string'), ('string2', 'string3'), ('string', 'string'), 'STRING')
>>> ' '.join( ' '.join(elem) if type(elem) is tuple else '' for elem in y )
'string string string2 string3 string string '
Upvotes: 0