String methods can be used to return new strings or a list of strings that have beenĀ modified in some way or to test the string for various conditions and return a Boolean. Some useful methods are as follows:
- endswith: Determines if the string ends with a substring
- startswith: Same asĀ endswith, but from the start
- split: Splits the string on characters (default is space) into a list of substrings
- rsplit: The same as split, but starts from the end of the string and works backwards
- splitlines: Splits the string at newlines into a list of substrings
- upper: Returns a copy of the string all in uppercase
- lower: Returns a copy of the string all in lowercase
- capitalize: Returns a copy of the string with just the first character in uppercase
We can create a simple playbook that will utilize some of these methods in a single task:
--- - name: demo the filters hosts: localhost gather_facts: false tasks: - name: string methods debug: msg: "{{ 'foo bar baz'.upper().split() }}"
The output is shown in the following screenshot:
As these are object methods, we need to access them with dot notation, rather than with a filter via |.