LG1
LG1

Reputation: 921

Python How to split a string and print a one line separated by backslash

I'm new to Python, and I am having some trouble splitting this string by the comma, then splitting it by the equal sign, reversing it, and print only the second value of each list within a list.

String to break up

text = "cn=username,ou=group1,ou=group2,dc=domain1,dc=enterprise"

End result

username/group1/group2/domain1/enterprise

Somethings I have tried

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)

The result is:

username/group1/group1/domain1/enterprise/

I would like to use ('/'.join()), but I do not know how to only get the second element of the inner list.

Upvotes: 2

Views: 1632

Answers (4)

Garrett Hyde
Garrett Hyde

Reputation: 5597

Here is a multiline solution:

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))

For a one-liner:

text = "cn=username,ou=group1,ou=group1,dc=domain1,dc=enterprise"

print("/".join([l.split("=")[-1] for l in text.split(",")]))

Upvotes: 1

user13715010
user13715010

Reputation:

You can also do one simple modification in your code in the list line i.e. print(output) modify it as print(output[:-1])

Upvotes: 2

Red
Red

Reputation: 27557

You can use re:

import re
text = "cn=username,ou=group1,ou=group2,dc=domain1,dc=enterprise"
print(re.sub(",.*?=","/",text[3:]))

Output:

username/group1/group2/domain1/enterprise

Upvotes: 1

Pavel Botsman
Pavel Botsman

Reputation: 863

text = "cn=username,ou=group1,ou=group2,dc=domain1,dc=enterprise"

result = [pair.split('=')[1] for pair in text.split(',')]
print('/'.join(result))

If you need a slash at the end, you can add it manually on the last line:

print('/'.join(result) + '/')

Upvotes: 2

Related Questions