1

Hi I have this function that maps and joins the elements of a list into a string. My question is that is there was a way to add quotation marks around all the elements that are originally strings in the list.

  def blahblahblah(input):

     code  = "result = %s\n" % (", ".join(map(str, input)))
     print code




  x = ["dasdad", 131]
  blahblahblah(x)

  //normal output ------result = dasdad, 131 
 //desired output ------result = 'dasdad', 131

3 Answers 3

2

Padraic has already answered your stated question quite well, so I won't duplicate his work here. Instead, I'm taking a leap and attempting to answer your question in a more general form.


It looks like you're trying to recreate Python literals in your formatted output. For objects like strings and numbers, the built-in repr function will do this for you.

>>> def blahblahblah(input):
...     code  = "result = %s\n" % (", ".join(map(repr, input)))  # Map repr instead of str
...     print code
... 
>>> blahblahblah(["dasdad", 131])
result = 'dasdad', 131

repr is one of the most versatile Python builtins for exploring and debugging, and its utility certainly isn't limited to string formatting. If you're not familiar with it already, I strongly suggest you become so!

Sign up to request clarification or add additional context in comments.

Comments

2

You can map str.format wrapping each element in whatever you want:

def blahblahblah(inp):
     code  = "result = {}\n".format(", ".join(map("'{}'".format, inp)))
     print code

So each element in your list will be wrapped in quotes in your output:

In [2]: x = ['dasdad', 131]

In [3]: blahblahblah(x)
result = 'dasdad', '131'

Or for just the str types, use isinstance:

def blahblahblah(inp):
     code  = "result = {}\n".format(", ".join(['"{}"'.format(s) if isinstance( s, str) else str(s) for s in inp)])
     print code

Which gives you:

In [5]: x = ["dasdad", 131]

In [6]: blahblahblah(x)
result = 'dasdad', 131

1 Comment

This will put quotes around every element of the list. He only wants around the first AFAIK.
1

you can add quotation mark to string first.

x = [ "\"" + i +"\"" if isinstance(i,str) else i for i in x]
code  = "result = %s\n" % (", ".join(map(str, x)))
print code

result = "dasdad", 131

print "result = %s\n" % (", ".join(map(str,  ["\"" + i +"\"" if isinstance(i,str) else i for i in x])))

1 Comment

You need change 'input' to 'x' in the first example.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.