0

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

Bhmmam
  • 11
  • 3
  • 1
    What criteria do you have? Do you always want to use camelCase to unpack the string? Or number of characters? Any specific use case? If you were to use camelCase and your string always follows that format, you could use a regular expression to split the string, if it always follows that pattern. Please add more information to understand your use case better. – Sergio Mar 20 '19 at 04:12
  • 1
    `*X` unpacks `X` into constituent items. If `X` is a string, then `*X` are individual characters. There are no other ways to interpret `*X`. – DYZ Mar 20 '19 at 04:39

1 Answers1

1

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' 
Sergio
  • 324
  • 2
  • 12
  • I appreciate your time Sergio, and I knew about the split() before but I was kinda looking for a way to do that with the string formatter – Bhmmam Mar 20 '19 at 04:27
  • Using the formatter, you can format floats, align the text, format as percentage and do other things within the curly braces, but you can't do string slicing. You could look into the formatter's [minilanguage](https://docs.python.org/3.5/library/string.html#format-specification-mini-language) to see what's possible. – Sergio Mar 20 '19 at 04:53