我一直在阅读有关字符串格式的Python 3.2文档,但它并没有真正帮助我解决这个特殊问题.
这是我正在尝试做的事情:
stats = { 'copied': 5, 'skipped': 14 }
print( 'Copied: {copied}, Skipped: {skipped}'.format( stats ) )
Run Code Online (Sandbox Code Playgroud)
上面的代码不起作用,因为format()调用不是读取字典值并使用它们代替我的格式占位符.如何修改我的代码以使用我的字典?
这段代码有什么问题?
dic = { 'fruit': 'apple', 'place':'table' }
test = "I have one {fruit} on the {place}.".format(dic)
print(test)
>>> KeyError: 'fruit'
Run Code Online (Sandbox Code Playgroud) 我想写一个带字符串和字典的方法.该方法应扫描字符串并将{word}内的每个单词替换为dic ["word"]的值.
例:
s = "Hello my name is {name} and I like {thing}"
dic = {"name": "Mike", "thing": "Plains"}
def rep(s, dic):
return "Hello my name is Mike and I like Plains"
Run Code Online (Sandbox Code Playgroud)
我的意思是它是一个简单的问题,易于解决,但我搜索了很好的python方式.
我有元组列表,我希望元组在索引处具有最小值1.例如,如果我的列表如下:
a =[('a', 2), ('ee', 3), ('mm', 4), ('x', 1)]
Run Code Online (Sandbox Code Playgroud)
我想要返回的元组('x', 1).
目前我正在使用sorted函数来获得这样的结果:
min=sorted(a, key=lambda t: t[1])[0]
Run Code Online (Sandbox Code Playgroud)
有更好的方法吗?也许有min功能?
我正在创建一个程序,通过以下输入计算一顿饭的总成本:meal_cost,tax_rate,tip_rate,number_eating
并使用函数调用将它们打印在字符串中.我查看了StackOverflow,但找不到适合我情况的问题(打印字符串函数返回的字典)
我有一个函数,它接受所有输入并返回一个字典输出.我想在函数调用的字符串中打印返回的值,所有这些都在同一行中.这是我试过的:
def calculatedCost(meal_cost,tax_rate,tip_rate,number_eating):
tax = round(float(meal_cost * tax_rate) / 100,2)
tip = round(float(meal_cost * tip_rate) / 100,2)
total_cost = round(meal_cost + tax + tip,2)
division = round(total_cost / number_eating,2)
return {'tax': tax, 'tip': tip, 'total_cost':total_cost, 'division':division}
print("The cost of your meal is: {total_cost}, the tax on your meal is: {tax}, the tip is equal to: {tip}, and the split total is: {division}".format(calculatedCost(62.75,5,20,2)))
Run Code Online (Sandbox Code Playgroud)
我得到这个错误:(我正在使用Processing)
KeyError: total_cost
processing.app.SketchException: KeyError: total_cost
at jycessing.mode.run.SketchRunner.convertPythonSketchError(SketchRunner.java:240)
at jycessing.mode.run.SketchRunner.lambda$2(SketchRunner.java:119)
at java.lang.Thread.run(Thread.java:748)
Run Code Online (Sandbox Code Playgroud) 我有一个公开为 http://localhost:8080/test/api/v1/qc/{id} 的 Http 端点用于删除,在进行此 API 删除调用时,我必须用正确的 id 替换
我使用 python 的 requests 模块尝试了以下方法
param = {
"id" : 1
}
requests.delete(url = http://localhost:8080/test/api/v1/qc/{id}, params=param)
Run Code Online (Sandbox Code Playgroud)
此 API 调用因错误而中断
ValueError: No JSON object could be decoded.
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
python ×6
dictionary ×2
string ×2
jython ×1
kwargs ×1
lambda ×1
list ×1
min ×1
processing ×1
python-3.x ×1