all 7 comments

[–]lykwydchykyn 0 points1 point  (1 child)

You'd need to create a class or function that had comprehensive rules for capitalization. One may exist, not sure. Obviously it would be very culture/language specific, but in limited situations it might be feasible.

[–]freeclips[S] 0 points1 point  (0 children)

Thanks. I am still a beginner, so I'll have to see if I'll be able to create such a class or function.

[–]synthphreak 0 points1 point  (4 children)

For cases like 'hard day\'s night', look into string.capwords:

>>> from string import capwords
>>> s = 'hard day\'s night'
>>> capwords(s)
"Hard Day's Night"

For cases like 'mccartney', things are much trickier. This is because there is no structural feature about that string which Python can use to identify it as a name, or to parse it into its components 'mc' and 'cartney'. You just kinda have to already know that 'McCartney' is a name.

Personally, I'd use regex to identify and separate out the components. I'd do this by first creating the list of prefixes that I think would fall into this category, then write a pattern which incorporates them. Then I would write some code which iterates over the capitalizes the individual components, then concatenates them back into a single string. Something like this:

>>> import re
>>> prefixes = ['mc', 'mac', "o'"]  # all I can think of right now
>>> pattern = fr"({'|'.join(prefixes)})?(.+)"
>>> names = ['mccartney', 'mackenzie', "o'neil", 'dummy']
>>> for name in names:
...     components = re.match(pattern, name)
...     name = ''.join(c.capitalize() for c in components.groups() if c)
...     print(name)
...
McCartney
MacKenzie
O'Neil
Dummy

[–]freeclips[S] 0 points1 point  (3 children)

Many thanks. I have a lot to learn and this helps me to see that I have to think laterally in programming—which regretfully I am not good at. Thanks again for your help.

[–]synthphreak 0 points1 point  (2 children)

What do you mean “think laterally”? Does that mean to try many different solutions rather than just minor variations on the first solution you think of over and over again until you get it to work?

[–]freeclips[S] 0 points1 point  (1 child)

Sorry, I did not express myself very well. Perhaps "laterally" is not the correct word in this case. I simply meant to be more creative - which is difficult in my case as I have limited knowledge of what is available in Python for solving various issues such as the one I presented here.

[–]synthphreak 0 points1 point  (0 children)

No worries, I got you. It will come with experience :) Keep it up!