0

因此,我编写了一个程序来格式化我在 Python 中的列表,以便以 HTML 形式编写为 JavaScript。看起来像这样

from django.template.defaultfilters import slugify
def js_format(cars):
   new_cars = []
   for car in cars:
       car = str(slugify(car))+'|'+car
       new_cars.append(car)
   return new_cars

dodge = ["Avenger","Caliber","Caravan","Challenger","Colt","D150","D250","D350","Dakota","Dart","Daytona","Durango","Durango Hybrid","Dynasty","Grand Caravan","Intrepid","Journey","Magnum","Monaco","Neon","Nitro","Omni","Raider","Ram 1500","Ram 2500","Ram 3500","Ram 50","Ram Van","Ram Wagon","Ramcharger","Shadow","Sprinter","SRT Viper","Spirit","Stealth","Stratus","Viper","W150","W250","W350"]

当我使用“闪避”列表中的程序时...

>>> js_format(dodge)
['avenger|Avenger', 'caliber|Caliber', 'caravan|Caravan', 'challenger|Challenger', 'colt|Colt', 'd150|D150', 'd250|D250', 'd350|D350', 'dakota|Dakota', 'dart|Dart', 'daytona|Daytona', 'durango|Durango', 'durango-hybrid|Durango Hybrid', 'dynasty|Dynasty', 'grand-caravan|Grand Caravan', 'intrepid|Intrepid', 'journey|Journey', 'magnum|Magnum', 'monaco|Monaco', 'neon|Neon', 'nitro|Nitro', 'omni|Omni', 'raider|Raider', 'ram-1500|Ram 1500', 'ram-2500|Ram 2500', 'ram-3500|Ram 3500', 'ram-50|Ram 50', 'ram-van|Ram Van', 'ram-wagon|Ram Wagon', 'ramcharger|Ramcharger', 'shadow|Shadow', 'sprinter|Sprinter', 'srt-viper|SRT Viper', 'spirit|Spirit', 'stealth|Stealth', 'stratus|Stratus', 'viper|Viper', 'w150|W150', 'w250|W250', 'w350|W350']

一切都按照我想要的方式格式化,除了我需要列表中的每个项目都用双引号引起来。我不知道如何更改python中的引号,因为python平等地识别单引号和双字符串。任何帮助,将不胜感激。

感谢您查看我的问题

4

3 回答 3

5

用于json.dumps()创建 Javascript 文字:

def js_format(cars):
   new_cars = ['{0!s}|{1}'.format(slugify(car)), car) for car in cars]
   return json.dumps(new_cars)

这将生成一个带有正确引用字符串的完整 JS 列表:

>>> js_format(dodge)
'["avenger|Avenger", "caliber|Caliber", "caravan|Caravan", "challenger|Challenger", "colt|Colt", "d150|D150", "d250|D250", "d350|D350", "dakota|Dakota", "dart|Dart", "daytona|Daytona", "durango|Durango", "durango-hybrid|Durango Hybrid", "dynasty|Dynasty", "grand-caravan|Grand Caravan", "intrepid|Intrepid", "journey|Journey", "magnum|Magnum", "monaco|Monaco", "neon|Neon", "nitro|Nitro", "omni|Omni", "raider|Raider", "ram-1500|Ram 1500", "ram-2500|Ram 2500", "ram-3500|Ram 3500", "ram-50|Ram 50", "ram-van|Ram Van", "ram-wagon|Ram Wagon", "ramcharger|Ramcharger", "shadow|Shadow", "sprinter|Sprinter", "srt-viper|SRT Viper", "spirit|Spirit", "stealth|Stealth", "stratus|Stratus", "viper|Viper", "w150|W150", "w250|W250", "w350|W350"]'
于 2012-11-30T21:23:05.003 回答
2

在 for 循环中,将分配更改为以下内容:

car = '"' + str(slugify(car)) + '|' + car + '"'

或者,您可以使用字符串格式:

car = '"{0}|{1}"'.format(str(slugify(car)), car)

我可能会误解这一点,你想js_format()返回一个 JSON 字符串吗?如果是这样,请使用您当前的函数,但import json在文件的顶部,并将您的 return 语句更改为return json.dumps(new_cars).

于 2012-11-30T21:21:39.800 回答
0

如果您需要您的字符串包含双引号 - 手动添加它们:

car = '"%s|%s"' % (slugify(car), ca)
于 2012-11-30T21:23:36.090 回答