Python: change capital letter

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

, eg:

string = "YannickMorin" 

I want him to become yannick-morin

At the moment, I can do everything in lower case by doing string.lower () , but how to put a dash when it finds the second uppercase letter.

+4
source share
4 answers

You can use regex

>>> import re
>>> split_res = re.findall('[A-Z][^A-Z]*', 'YannickMorin')
['Yannick', 'Morin' ]
>>>'-'.join(split_res).lower()
+5
source

This is more of a challenge 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'
+1
source

, , . .

>>> import re
>>> re.sub(r'\B([A-Z])', r'-\1', "ThisIsMyText").lower()
'this-is-my-text'
+1

lower() , , . . :

strAsList = list(string)
strAsList[0] = strAsList[0].lower()
strAsList[7] = strAsList[7].lower()
strAsList.insert(7, '-')
print (''.join(strAsList))
0

Source: https://habr.com/ru/post/1614779/


All Articles