-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathleftpad.py
55 lines (40 loc) · 1.13 KB
/
leftpad.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
# Для интереса написать аналог NPM leftpad.
#
# leftpad = require('left-pad')
#
# leftpad('foo', 5)
# // => " foo"
#
# leftpad('foobar', 6)
# // => "foobar"
#
# leftpad(1, 2, 0)
# // => "01"
def leftpad(text: str | int, size: int, ch: str | int = " "):
text = str(text)
ch = str(ch)
text_size = len(text)
return ch * (size - text_size) + text
# Версия с использованием общего алгоритм
def leftpad2(text: str | int, size: int, ch: str | int = " "):
text = str(text)
text_size = len(text)
pad_len = size - text_size
if pad_len <= 0:
return text
ch = str(ch)
result = ""
for i in range(pad_len):
result += ch
result += text
return result
if __name__ == "__main__":
assert leftpad("foo", 5) == " foo"
assert leftpad("foobar", 6) == "foobar"
assert leftpad(1, 2, 0) == "01"
assert leftpad("foo", 5) == leftpad2("foo", 5)
assert leftpad("foobar", 6) == leftpad2("foobar", 6)
assert leftpad(1, 2, 0) == leftpad2(1, 2, 0)