Python 是否可以使用字符串格式拆分字符串值?
编辑: 我一直在使用python 2.7.5 另一编辑: 阐明更改需要在模板中,而不是在处理字典的代码中 我正在使用字符串格式化程序从模板构建路径 我知道我能做到:Python 是否可以使用字符串格式拆分字符串值?,python,string,split,format,Python,String,Split,Format,编辑: 我一直在使用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) # Resu
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'
'/usr/Python/Monty'
这也适用于您的第一个示例:
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/Luxury/Raymond'
'/usr/Python/Monty'
作为旁注,在格式化中使用解包(**
)来删除字符串本身中的\uuuu getitem\uuuu
调用更像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 3.6开放,可以使用:
/usr/Luxury/Raymond
/usr/Python/Monty
但是,如果您想坚持Python 2中的dict样式格式,可以使用当前模板和一个小包装器类来清理字典值:
class Wrapper(object):
__slots__ = ('sep', 'dct')
def __init__(self, dct, sep='-'):
self.sep = sep
self.dct = dct
def __getitem__(self, key):
return self.dct[key].split(self.sep)[0]
template = '/usr/{user[last]}/{user[first]}'
for usr in map(Wrapper, users):
path = template.format(user=usr)
print(path)
/usr/Luxury/Raymond
/usr/Python/Monty
该死!这看起来正是我想要的,但不幸的是,我被困在Python2@RyandeKleerPython2很快就会被淘汰,所以不管怎样,将代码库迁移到Python3对您来说可能是有意义的。@Ajax1234绝对是,为了做好准备,我们正在尽可能地编写2/3合规性,但我们不能扣动扳机:在某些软件应用程序(VFX/电影行业)做出这一转换之前,我们一直停留在2:(@RyandeKleer啊,我明白。@MosesKoledoye包装器假设有一个分隔符,问题是我不能。这就是为什么我需要让编写模板的人(非程序员)来选择也许我应该澄清我的问题…我的限制是我不能用代码分割字符串,我必须依靠模板字符串来告诉python如何提取项。
{key:val.split(“-”[0]如果key==“last”else val for key,val in currentUser.items()}
只拆分姓氏。我很乐意编写一个自定义字符串格式化程序,将此行为引入规范,但如果该功能本机已经存在,我不想重新发明轮子。