Input : UserID/ContactNumber
Output: user-id/contact-number
I have tried the following code:
s ="UserID/ContactNumber"
list = [x for x in s]
for char in list:
if char != list[0] and char.isupper():
list[list.index(char)] = '-' + char
fin_list=''.join((list))
print(fin_list.lower())
but the output i got is:
user-i-d/-contact-number
You could use a regular expression with a positive lookbehind assertion:
>>> import re
>>> s ="UserID/ContactNumber"
>>> re.sub('(?<=[a-z])([A-Z])', r'-\1', s).lower()
'user-id/contact-number'
What about something like that:
s ="UserID/ContactNumber"
so = ''
for counter, char in enumerate(s):
if counter == 0:
so = char
elif char.isupper() and not (s[counter - 1].isupper() or s[counter - 1] == "/"):
so += '-' + char
else:
so += char
print(so.lower())
What did I change from your snippet?
I have add a check on the previous char, to not consider when the previous is upper (for the D of ID) or when the previous is \ for the C of Contact.
You are also editing the list list
while iterating on it's element, that is dangerous.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With