Bhmmam
Bhmmam

Reputation: 11

unpack a string to an argument sequence

a beginner question: how to unpack a string to an argument sequence:

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

I'm not sure how to set up the delimiter with longer words but I tried the camalCase and it didn't work

'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' 

edited:how to add a specifier so the string could be split by the camalCase or even a specific character like space

Upvotes: 0

Views: 255

Answers (1)

Sergio
Sergio

Reputation: 334

For the second case you would need to separate the string by camel case and for that we can use this neat function.

That function will return a list of strings separated by camel case. We can then use that to print what we want.

Beware that if your original string has less than 3 capital letters you'll get an IndexError: tuple index out of range. If you have more, that wouldn't be a problem.

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' 

If you wish to separate the string by something simpler, like a space or comma, then you can use the str.split() method.

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' 

Upvotes: 1

Related Questions