[英]How to convert the following string in python?
Input : UserID/ContactNumber 输入:UserID / ContactNumber
Output: user-id/contact-number 输出: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: 您可以使用具有正向lookbehind断言的正则表达式 :
>>> 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? 我从你的代码片段改变了什么?
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. 我已经添加了对前一个字符的检查,以便不考虑前一个是上限(对于ID的D)还是前一个是\\对于C的接触。
You are also editing the list list
while iterating on it's element, that is dangerous. 您正在编辑列表
list
同时迭代它的元素,这很危险。
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
用户ID /接触数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.