How to convert the following line in python?

Login: UserID / ContactNumber

Output: user ID / contact number

I 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 result is:

  user-i-d/-contact-number
+4
source share
3 answers

You can use regex with a positive lookbehind statement:

>>> import re
>>> s  ="UserID/ContactNumber"
>>> re.sub('(?<=[a-z])([A-Z])', r'-\1', s).lower()
'user-id/contact-number'
+7
source

How about something like this:

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 have I changed from your fragment?

  • You checked if this is the first char, and if it is a top char.
  • I added a check for the previous char, so as not to take into account when the previous one is upper (for D identifier) ​​or when the previous one is \ for C contact.

  • list, , .

+2

-

s ="UserID/ContactNumber"

new = []
words = s.split("/")

for word in words:
    new_word = ""
    prev = None
    for i in range(0, len(word)):
        if prev is not None and word[i].isupper() and word[i-1].islower():
            new_word = new_word  + "-" + word[i]
            prev = word[i]
            continue
        new_word = new_word  + word[i]
        prev = word[i]
    new.append(new_word.lower())

print "/".join(new)

/-

-1

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


All Articles