Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert the following string in python?

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
like image 699
shasha Avatar asked Feb 07 '23 04:02

shasha


2 Answers

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'
like image 70
Eugene Yarmash Avatar answered Feb 08 '23 18:02

Eugene Yarmash


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?

  • You were checking if this is the first char and if it is a upper char.
  • 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.

  • I have instead create an output string to store the new values
like image 26
Xavier C. Avatar answered Feb 08 '23 18:02

Xavier C.