How can I do string concatenation, or string replacement in YAML?
You can use a repeated node, like this:
user_dir: &user_home /home/user
user_pics: *user_home
I don't think you can concatenate though, so this wouldn't work:
user_dir: &user_home /home/user
user_pics: *user_home/pics
It's surprising, since the purpose of YAML anchors & references is to factor duplication out of YAML data files, that there isn't a built-in way to concatenate strings using references. Your use case of building up a path name from parts is a good example -- there must be many such uses.
Fortunately there's a simple way to add string concatenation to YAML via custom tags in Python.
import yaml
## define custom tag handler
def join(loader, node):
seq = loader.construct_sequence(node)
return ''.join([str(i) for i in seq])
## register the tag handler
yaml.add_constructor('!join', join)
## using your sample data
yaml.load("""
user_dir: &DIR /home/user
user_pics: !join [*DIR, /pics]
""")
Which results in:
{'user_dir': '/home/user', 'user_pics': '/home/user/pics'}
You can add more items to the array, like " "
or "-"
, if the strings should be delimited.