code_junkie

Formatting a data structure into a comma-separated list of arguments

Nov 12th, 2011
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. result = ''
  2. args = ['a', 'b', 'c', 'd']
  3.  
  4. i = 0
  5. for arg in args:
  6. if i != 0: result += arg
  7. else: result += arg + ', '
  8. i += 1
  9.  
  10. result = 'function (' + result + ')
  11.  
  12. 'function(%s)' % ', '.join(args)
  13.  
  14. 'function(a, b, c, d)'
  15.  
  16. result = 'function (%s)' % ', '.join(map(str,args))
  17.  
  18. Traceback (most recent call last):
  19. File "<stdin>", line 1, in <module>
  20. TypeError: sequence item 0: expected string, int found
  21.  
  22. >>> d = {'d':5, 'f':6.0, 'r':"BOB"}
  23. >>> ','.join(d)
  24. 'r,d,f'
  25.  
  26. >>> d = {'d':5, 'f':6.0, 'r':"BOB"}
  27. >>> result = 'function (%s)' % ', '.join(map(str, d.values()))
  28. >>> result
  29. 'function (BOB, 5, 6.0)'
  30.  
  31. >>> l = list()
  32. >>> for val in d.values():
  33. ... try:
  34. ... v = float(val) #half-decent way of checking if something is an int, float, boolean
  35. ... l.append(val) #if it was, then append the original type to the list
  36. ... except:
  37. ... #wasn't a number, assume it's a string and surround with quotes
  38. ... l.append(""" + val + """)
  39. ...
  40. >>> result = 'function (%s)' % ', '.join(map(str, l))
  41. >>> result
  42. 'function ("BOB", 5, 6.0)'
Add Comment
Please, Sign In to add comment