4

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
4
  • 2
    It is generally a bad idea to modify a list as you iterate over it. Commented Sep 9, 2016 at 14:43
  • 1
    You will have to special case consecutive capital chars. Also note that list(s) gives you a list of characters, and list is a bad name for your own variable. Commented Sep 9, 2016 at 14:45
  • 2
    @FamousJameous only really if you're changing its length. Commented Sep 9, 2016 at 14:46
  • Even if you are only changing the list, it impairs developer reasoning. In code review I'd suggest list_in and list_out as separate lists even just for developer reasoning alone. Commented Sep 9, 2016 at 14:57

3 Answers 3

7

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'
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

Instead of giving a new solution, tell what is wrong in his/her logic?
@helloV, You are totally right, I've edit my answer to explain the change I've made from his/her code
-1

I did something like this

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)

user-id/contact-number

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.