Skip to main content
 首页 » 编程设计

python之可以使用字符串格式来拆分字符串值吗

2024年10月01日34lautakyan007

编辑: 我坚持使用 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__ 调用更符合 Pythonic:

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()})