5

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.

6
  • I don't understand the use case here. Commented Jul 20, 2017 at 7:27
  • 2
    I'm sure that if you'll try you'll be able to concatenate strings in Python!
    – Nir Alfasi
    Commented Jul 20, 2017 at 7:27
  • 2
    '"' + a + '"'
    – cs95
    Commented Jul 20, 2017 at 7:27
  • a = "apple" initially and will end up being a = '"apple"' unless apple is a variable and not a string to begin with
    – Ma0
    Commented Jul 20, 2017 at 7:28
  • What do you mean "only work when printing the string?" Commented Jul 20, 2017 at 7:37

4 Answers 4

23

Beautiful usage in python

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

in python 3.6 (or above)

b = f'"{a}"'

work same!

2
  • Fstrings are Python 3.6+ fyi
    – Luke
    Commented Jul 20, 2017 at 9:24
  • It's awesome! : )
    – Jiun Bae
    Commented Jul 21, 2017 at 1:21
6
b = '"' + a + '"'

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

1
  • 1
    Or if you happen to somehow need to print("\"") --> "
    – Luke
    Commented Jul 20, 2017 at 9:25
3
def add_quote(a):
    return '"{0}"'.format(a)

and call it:

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

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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.