Sammy Herring Sammy Herring - 3 months ago 10
Python Question

Print function in python giving strings with brackets?

When I print a statement in python it is given in the form ['Hello World']. I'm not certain why and am looking to fix this problem and I believe it may be related to the formatting of the code.

query = input("Enter your query: ").lower()
brands = ["apple", "android", "windows"]
brand = set(brands).intersection(query.split())
brand = str(brand.translate({ord('['): '', ord(']'): ''}))
print(brand)


which gives me the output (from the print function) when given a correct query of apple:

{'apple'}


I would appreciate any solutions,

Thanks,

Python Shell: v3.5.2

Answer

Curly braces '{' and '}' are used for sets and dictionaries.

# e.g.
print(set(brands))
{'apple', 'android', 'windows'}

In your case you create a set by intersecting set(brands) with the query, then you convert the set to a string, which will include the curly braces.

One simple solution to exclude the braces, while still separating all possible matches is:

brand = set(brands).intersection(query.split())
print(', '.join(brand))