J.Smith
J.Smith

Reputation: 11

How to re-format a string (for a novice)

A quick question from a Python novice... the short version is : How do I re-format a string like ('A', 'B', 'C') into ABC?

Background: I'm writing a program that uses itertools.product to get all combinations of a set of letters x times. Eventually I want to search a much larger file to see how often each of those combinations occurs (similar to this post). So I need to ensure that the results from itertools.product are simply concatenated together, without the formatting characters and spaces. Each approach I've tried has failed or caused errors I don't know how to resolve. It seems like there'd be an easy way to do this...

Can anyone help me find a way to take strings like ('A', 'B', 'C') and convert them to ABC?

Thanks in advance for any assistance.

Upvotes: 1

Views: 37

Answers (2)

Zizouz212
Zizouz212

Reputation: 4998

If you have a list, or tuple, just do this:

concatenated_string = ''.join(list_of_values)

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107287

Use a list comprehension within join function :

>>> s="('A', 'B', 'C')"
>>> ''.join([i for i in s if i.isalpha()])
'ABC'

Or use ast.literal_eval to convert your string to a tuple object then pass it to join:

>>> from ast import literal_eval
>>> ''.join(literal_eval(s))
'ABC'

Upvotes: 2

Related Questions