4

I can't figure out how to replace the second uppercase letter in a string in python.

for example:

string = "YannickMorin" 

I want it to become yannick-morin

As of now I can make it all lowercase by doing string.lower() but how to put a dash when it finds the second uppercase letter.

Javier Conde
  • 2,553
  • 17
  • 25
Yannick
  • 3,553
  • 9
  • 43
  • 60
  • you can use `re` module to `re.sub` all upper-case letters with `-\1` then make everything lower case. or use `re.split` to split at each capital letter then `'-'.join` and then convert to lower case – R Nar Nov 06 '15 at 17:58
  • Here's a similar one: http://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-camel-case – Javier Conde Nov 06 '15 at 18:03

4 Answers4

5

You can use Regex

>>> import re
>>> split_res = re.findall('[A-Z][^A-Z]*', 'YannickMorin')
['Yannick', 'Morin' ]
>>>'-'.join(split_res).lower()
Shankar
  • 846
  • 8
  • 24
1

This is more a task for regular expressions:

result = re.sub(r'[a-z]([A-Z])', r'-\1', inputstring).lower()

Demo:

>>> import re
>>> inputstring = 'YannickMorin'
>>> re.sub(r'[a-z]([A-Z])', r'-\1', inputstring).lower()
'yannic-morin'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Find uppercase letters that are not at the beginning of the word and insert a dash before. Then convert everything to lowercase.

>>> import re
>>> re.sub(r'\B([A-Z])', r'-\1', "ThisIsMyText").lower()
'this-is-my-text'
dlask
  • 8,776
  • 1
  • 26
  • 30
0

the lower() method does not change the string in place, it returns the value that either needs to be printed out, or assigned to another variable. You need to replace it.. One solution is:

strAsList = list(string)
strAsList[0] = strAsList[0].lower()
strAsList[7] = strAsList[7].lower()
strAsList.insert(7, '-')
print (''.join(strAsList))
ergonaut
  • 6,929
  • 1
  • 17
  • 47