简体   繁体   中英

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

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?

  • 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM