输入:UserID / ContactNumber
输出:user-id / contact-number
我尝试过以下代码:
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())
但我得到的输出是:
user-i-d/-contact-number
答案 0 :(得分:7)
你可以使用regular expression带有正面的后瞻断言:
>>> import re
>>> s ="UserID/ContactNumber"
>>> re.sub('(?<=[a-z])([A-Z])', r'-\1', s).lower()
'user-id/contact-number'
答案 1 :(得分:2)
这样的事情:
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())
我从您的代码段中更改了什么?
我已经添加了对前一个字符的检查,以便不考虑前一个是上限(对于ID的D)还是前一个是\对于C的接触。
您正在编辑列表list
,同时迭代它的元素,这很危险。
答案 2 :(得分:-1)
我做了类似的事
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)
用户ID /接触数目