简体   繁体   中英

How to join list from th yaml file in python

How to Join the list based on YAML file, i have below file which need to join by space delimitation.

$ cat File.yml
---
fruits:
 - orange
 - banana
 - apple
 - strawberry
 - berry
 - cherry
... 

What i tried:

>>> import yaml
>>> with open('File.yml') as f:
...   result = yaml.safe_load(f)
...   print(result)
...
{'fruits': ['orange', 'banana', 'apple', 'strawberry', 'berry', 'cherry']}

Can we do something {{ fruits[ item ] | join(' ') }}" {{ fruits[ item ] | join(' ') }}" ?

Desired:

"orange banana apple strawberry berry cherry"

I don't require "," in the result.

Just try this:

import yaml


with open('File.yml') as f:
    result = yaml.safe_load(f)
    print(' '.join(result['fruits']))

Output:

orange banana apple strawberry berry cherry

Just going on top of what you already have.

>>> with open("File.yml") as f:
...   result = yaml.safe_load(f)
>>> " ".join(result["fruits"])
"orange banana apple strawberry berry cherry"

You can refer to the Python docs for a more in-depth description on the syntax of the .join . The gist of it is that we need

str.join(iterable)

In this case, we want to join by empty spaces, " " , and we want to iterate through the contents of result["fruits"] " to join the items into one string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM