Debian Codegraph @

cylc/flow/jinja/filters/pad.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 """Filter for padding strings to a set number of chars."""
17
18 from typing import Union
19
20
21 def pad(value: str, length: Union[int, str], fillchar: str = ' '):
22 """Pads a string to some length with a fill character
23
24 Useful for generating task names and related values in ensemble workflows.
25
26 Args:
27 value:
28 The string to pad.
29 length:
30 The length for the returned string.
31 fillchar:
32 The character to fill in surplus space (space by default).
33
34 Returns:
35 str: value padded to the left with fillchar to length length.
36
37 Python Examples:
38 >>> pad('13', 3, '0')
39 '013'
40 >>> pad('foo', 6)
41 ' foo'
42 >>> pad('foo', 2)
43 'foo'
44
45 Jinja2 Examples:
46 .. code-block:: cylc
47
48 {% for i in range(0,100) %} # 0, 1, ..., 99
49 {% set j = i | pad(2,'0') %}
50 [[A_{{j}}]] # [[A_00]], [[A_01]], ..., [[A_99]]
51 {% endfor %}
52
53 """
54 return str(value).rjust(int(length), str(fillchar))