activelearner
activelearner

Reputation: 7805

Python - How to append double quotes to a string and store as new string?

I am using Python 2.6+ and would like to append double quotes to a string and store it as a new string variable. I do not want to print it but use it later in my python script.

For example:

a = 'apple'
b = some_function(a) --> b would be equal to '"apple"'

How can I do this? All the solutions that I have looked at so far only work when printing the string.

Upvotes: 5

Views: 83040

Answers (4)

Hadi Farhadi
Hadi Farhadi

Reputation: 1771

def add_quote(a):
    return '"{0}"'.format(a)

and call it:

a = 'apple'
b = add_quote(a) # output => '"apple"'

Upvotes: 3

Md. Rezwanul Haque
Md. Rezwanul Haque

Reputation: 2950

You can try this way :

def some_function(a):
    b = '"' + a + '"'
    return b

if __name__ == '__main__':
    a = 'apple'
    b = some_function(a)
    print(b)

Output:

"apple"

Upvotes: 1

Jiun Bae
Jiun Bae

Reputation: 560

Beautiful usage in python

b = '"{}"'.format(a)

in python 3.6 (or above)

b = f'"{a}"'

work same!

Upvotes: 24

perigon
perigon

Reputation: 2095

b = '"' + a + '"'

Notice that I am enclosing the double quotes in single quotes - both are valid in Python.

Upvotes: 7

Related Questions