Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是否可以使用字符串格式拆分字符串值?_Python_String_Split_Format - Fatal编程技术网

Python 是否可以使用字符串格式拆分字符串值?

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

编辑: 我一直在使用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'
决定选择:

  • 拆分哪个键
  • 凭什么性格
  • 从拆分中使用哪个索引
必须来自模板字符串;如果当前的迷你语言无法实现这一点,我将不得不编写一个自定义格式化程序

免责声明:我知道,这个例子有点做作,不实用。我实际上是在处理一个数据库,其中两个关键信息位存储在一个字段中,并用下划线-u-。我知道我可以在从数据库中提取数据后对其进行后处理,但由于每个项目对该字段的约定不同,我甚至不能假设拆分操作是有效的(某些项目上的某些值不会有下划线问题)。我希望能够为用户提供一种模板“语言”,让每个项目自己决定如何提取数据,适应他们选择的任何命名约定,并相应地配置他们的模板,而不是围绕每个约定编写解决方案


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()}
只拆分姓氏。我很乐意编写一个自定义字符串格式化程序,将此行为引入规范,但如果该功能本机已经存在,我不想重新发明轮子。