我是Python的新手,我在用逗号拆分这个字符串,然后用等号拆分它,颠倒它,并且只打印列表中每个列表的第二个值时遇到了一些问题。
要拆分的字符串
text = "cn=username,ou=group1,ou=group2,dc=domain1,dc=enterprise"
最终结果
username/group1/group2/domain1/enterprise
一些我尝试过的东西
text = "cn=username,ou=group1,ou=group1,dc=domain1,dc=enterprise"
list_of_list = list(l.split('=') for l in (text.split(',')) )
print(text)
print(list_of_list)
output = ""
for i in list_of_list:
output += i[1] + '/'
print(output)
结果是:
username/group1/group1/domain1/enterprise/
我想使用('/'.join()),但我不知道如何只获取内部列表的第二个元素。
发布于 2020-06-09 16:04:05
text = "cn=username,ou=group1,ou=group2,dc=domain1,dc=enterprise"
result = [pair.split('=')[1] for pair in text.split(',')]
print('/'.join(result))
如果您需要在末尾添加斜杠,可以在最后一行手动添加:
print('/'.join(result) + '/')
发布于 2020-06-09 16:09:13
您还可以对列表行中的代码进行简单的修改,即print(output)
将其修改为print(output[:-1])
发布于 2020-06-09 16:21:57
下面是一个多行解决方案:
text = "cn=username,ou=group1,ou=group1,dc=domain1,dc=enterprise"
output = []
# Split on the ","
for component in text.split(","):
# Split the "=" into key/value pairs
key, value = component.split("=")
# Append only the value to the output list
output.append(value)
print("/".join(output))
对于一行代码:
text = "cn=username,ou=group1,ou=group1,dc=domain1,dc=enterprise"
print("/".join([l.split("=")[-1] for l in text.split(",")]))
https://stackoverflow.com/questions/62286825
复制