0

Using Python version : 2.7.5 OS: Linux

Path = ['azure_mico docker_telco /AWS Cloud/Test/DEMO/Service/DEV:', 'azure_mico google_telco /AWS Cloud/Test/Blender/Service/QA1:']

Actually the Path list is too lengthy, It has more than 200 values, bu just for an example I have provided only two;

I want to split the above list, and add a string before each value, and print the output. The expected output should look like below:

Cloud: azure_mico , Service: docker_telco , CloudPath: /AWS Cloud/Test/DEMO/Service/DEV

Cloud: azure_mico , Service: google_telco , CloudPath: /AWS Cloud/Test/Blender/Service/QA1
itgeek
  • 549
  • 1
  • 15
  • 33
  • What is the splitting criteria? If you need to split on whitespaces, have a look here: https://stackoverflow.com/questions/4309684/split-a-string-with-unknown-number-of-spaces-as-separator-in-python – Valentino Apr 22 '19 at 17:29

1 Answers1

1

A simple for loop and the str.split() method should be enough for this.

for item in Path:
    split_item = item.split(' ')  # Split each item by spaces
    cloud, service = split_item[0], split_item[1]  # Take the first two
    cloudpath = ' '.join(split_item[2:])           # merge the third and onward back into a single string
    # then, print everything in the desired format. 
    # You could also output this information another way, now that you have it.
    print(f"Cloud: {cloud} , Service: {service} , CloudPath: {cloudpath}\n")

Executed, prints the following:

Cloud: azure_mico , Service: docker_telco , CloudPath: /AWS Cloud/Test/DEMO/Service/DEV:
Cloud: azure_mico , Service: google_telco , CloudPath: /AWS Cloud/Test/Blender/Service/QA1:
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • print(f"Cloud: {cloud} , Service: {service} , CloudPath: {cloudpath}\n") ^ SyntaxError: invalid syntax – itgeek Apr 22 '19 at 17:35
  • Are you sure you're using python3? In python2 you might need to instead do `"Cloud: {} , Service: {} , CloudPath: {}\n".format(cloud, service, cloudpath)`, as format strings don't exist – Green Cloak Guy Apr 22 '19 at 18:10
  • Yeah correct, I removed "f" and it works find. Thank you. – itgeek Apr 22 '19 at 18:13
  • Is there anyway we can count unique values for "Cloud" key ? e.g. value of cloud is azure_mico, and it being mentioned twice. and also I would like to print only unique values for cloud key. – itgeek Apr 22 '19 at 19:24
  • You could make an empty list (e.g. `past_clouds = []`) before starting the loop, and then each iteration of the loop check `if cloud in past_clouds: continue` to skip that iteration. And if you pass that check, add the new value by doing `past_clouds.append(cloud)`. If your question is more complicated, I'd advise submitting a new question on StackOverflow. – Green Cloak Guy Apr 22 '19 at 21:23
  • I found the solution. Thank you. Really appreciated your assistance. – itgeek Apr 23 '19 at 00:45