Reputation: 705
How can I not print the quotes around a string? I understand that this is a string, as a result Python is adding the quotes.
To give more context:
def a(content):
return {'row_contents': content}
print(a("Hello"))
This gives output as:
{'row_contents': 'Hello'}
I want to remove the quotes around Hello while returning this (something as below)
{'row_contents': Hello}
Is there an easy way to achieve this?
Upvotes: 0
Views: 1776
Reputation: 11374
I still believe this question has a high probability of being an XY problem.
However, regarding your question as it stands: If you don't want to modify print
, you're only left with modifying the return value of your function a
. Your comment above says:
I want to return a
dict
This sounds like simply returning a modified string representation of {'row_contents': content}
isn't really what you're looking for. Yet, dict.__repr__
itself is read-only, so I guess the closest solution would be to return an instance of a custom dict
subclass:
class CustomDict(dict):
def __repr__(self):
return "{" + ", ".join([repr(k) + ": " + str(v) for k, v in self.items()]) + "}"
def a(content):
return CustomDict({'row_contents': content})
print(a("Hello"))
print(isinstance(a("Hello"), dict))
Which prints:
{'row_contents': Hello}
True
You might need to improve CustomDict.__repr__
depending on what modifications are necessary to provide the desired output. You could also modify the original string representation super().__repr__()
.
Upvotes: 1
Reputation: 89
you can ues f string
def a(content):
return f"{{'row_contents': {content}}}"
print(a("Hello"))
or just this:
def a(content):
return "{'row_contents':"+content+"}"
Output:
{'row_contents': Hello}
Upvotes: 1
Reputation: 5975
You can simply get the string representation of the dictionary and remove the single quotes.
def a(content):
return {'row_contents': content}
def print_dict_without_quotes(d):
print(str(d).replace("'", "").replace('"', ''))
print_dict_without_quotes(a("Hello"))
Output:
{row_contents: Hello}
Upvotes: 0