将字符串解压缩为参数序列

时间:2019-03-20 04:04:52

标签: python python-3.x string-formatting

一个初学者的问题: 如何将字符串解压缩为参数序列:

'{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
'c, b, a'

我不确定如何用更长的单词设置定界符,但是我尝试了camalCase,但没有用

'sir {}, so your family's name is {}, and you were born in {}'.format(*"HmmamKhoujaSyria")
 #'sir Hmmam, so your family's name is Khouja, and were born in Syria' 

编辑:如何添加说明符,以便字符串可以被camalCase甚至是空格之类的特定字符分割

1 个答案:

答案 0 :(得分:1)

对于第二种情况,您需要按驼峰大小写分隔字符串,为此,我们可以使用this neat function

该函数将返回由驼峰大小写分隔的字符串列表。然后,我们可以用它来打印我们想要的东西。

请注意,如果您的原始字符串少于3个大写字母,则会得到IndexError: tuple index out of range。如果您还有更多,那将不是问题。

from re import finditer

def camel_case_split(identifier):
    matches = finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)', identifier)
    return [m.group(0) for m in matches]

s = "HmmamKhoujaSyria"
l = camel_case_split(s)
'sir {}, so your family\'s name is {}, and you were born in {}'.format(*l)
#'sir Hmmam, so your family's name is Khouja, and were born in Syria' 

如果您希望使用更简单的分隔符(例如空格或逗号)来分隔字符串,则可以使用str.split()方法。

s = "Hmmam Khouja Syria"
l = s.split(" ")
'sir {}, so your family\'s name is {}, and you were born in {}'.format(*l)
#'sir Hmmam, so your family's name is Khouja, and were born in Syria'