编辑: 我被 python 2.7.5 困住了......
另一个编辑: 澄清需要在模板中进行更改,而不是在处理字典的代码中。
我正在使用字符串格式化程序从模板构建路径。
我知道我能做到:
currentUser = {'first': "Monty", 'last': "Python"}
template = '/usr/{user[last]}/{user[first]}' # will come from a config file
template.format(user=currentUser)
# Result: '/usr/Python/Monty'
但是在
的情况下currentUser = {'first': "Raymond", 'last': "Luxury-Yacht"}
有没有办法通过 -
进行拆分并使用索引?
# something like:
template = '/usr/{user[last].split(-)[0]/{user[first]}' # will come from a config file
template.format(user=currentUser)
# Result: '/usr/Luxury/Raymond'
选择的决定:
- 要分割哪个键
- 按什么字符
- 要使用拆分中的哪个索引
必须来自模板字符串;如果当前的迷你语言无法实现这一点,我将不得不编写一个自定义格式化程序。
免责声明:我知道这个例子有点做作,而且不实用。我实际上正在处理一个数据库,其中两个关键信息位存储在单个字段中,并用下划线 -_- 连接。我知道我可以在从数据库中提取数据后对数据进行后处理,但由于每个项目的该字段的约定不同,我什至不能假设拆分操作是有效的(某些项目上的某些值赢得了没有下划线问题)。我希望能够为用户提供一种模板“语言”,而不是围绕每个约定编写解决方案,以便每个项目自己确定如何提取该数据,适应他们选择的任何命名约定,并相应地配置其模板.
TL/DR:我不是在寻找修复传入数据的解决方案 - 我正在探索使用 Python 的字符串格式迷你语言分割字符串的可能性。
最佳答案
您可以使用字典理解:
currentUser = {'first': "Raymond", 'last': "Luxury-Yacht"}
template = '/usr/{user[last]}/{user[first]}'
template.format(user={a:b.split('-')[0] if '-' in b else b for a, b in currentUser.items()})
输出:
'/usr/Luxury/Raymond'
这也适用于您的第一个示例:
currentUser = {'first': "Monty", 'last': "Python"}
template = '/usr/{user[last]}/{user[first]}'
template.format(user={a:b.split('-')[0] if '-' in b else b for a, b in currentUser.items()})
输出:
'/usr/Python/Monty'
顺便说一句,在格式中使用解包 (**
) 来删除字符串本身中的 __getitem__
调用更符合 Python 风格:
currentUser = {'first': "Raymond", 'last': "Luxury-Yacht"}
template = '/usr/{last}/{first}'.format(**{a:b.split('-')[0] if '-' in b else b for a, b in currentUser.items()})
关于python - 可以使用字符串格式来分割字符串值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47358107/