Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/python-wasm
Path: blob/main/python/pylang/test/str.py
1396 views
1
# vim:fileencoding=utf-8
2
# License: BSD
3
# Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
4
# globals: assrt
5
6
import encodings
7
ae = assrt.equal
8
9
# Test literals
10
11
ae(r'\n', '\\n')
12
ae('\n'.charCodeAt(0), 10)
13
ae('\'', "'")
14
ae('\76'.charCodeAt(0), 62) # octal escapes
15
ae('\x2a'.charCodeAt(0), 0x2a) # hex escapes
16
ae('\u2028'.charCodeAt(0), 0x2028)
17
ae("\U0001F431", '🐱')
18
ae("\U0001F431", '🐱')
19
ae("\N{nbsp}", '\u00a0')
20
ae("\N{NBSp}", '\u00a0')
21
for qs, aval in [['a', True], ['A', False]]:
22
ae(str.islower(qs), aval)
23
ae(str.islower(new String(qs)), aval)
24
ae(str.isupper(qs), aval ^ True)
25
ae(str.isupper(new String(qs)), aval ^ True)
26
27
# Test format()
28
29
def test():
30
args = Array.prototype.slice.call(arguments, 1)
31
ae(arguments[0], str.format.apply(None, args))
32
33
def test_throws():
34
args = Array.prototype.slice.call(arguments)
35
def f():
36
return str.format.apply(None, args[1:])
37
assrt.throws(f, args[0])
38
39
def test_interpolation():
40
a, b, c = 1, ['x'], 30000
41
ae(f'{a}', '1')
42
ae(f'0{a}', '01')
43
ae(f'0{a}2', '012')
44
ae(f'{a}{b[-1]}', '1x')
45
ae(f'{c:,d}', (30000).toLocaleString())
46
ae(f'\n', '\n')
47
ae(f'{a}\\{b[0]}', '1\\x')
48
ae(f'x\n\ny', 'x\n\ny')
49
ae(f'{a=}', 'a=1')
50
somevar = {'x': 1}
51
ae(f'{somevar.x=}', 'somevar.x=1')
52
53
somevar = 33
54
test('somevar=33', '{somevar=}', somevar=somevar)
55
somevar = {'v': 'x'}
56
test('somevar.v=x', '{somevar.v=}', somevar=somevar)
57
test(' 1 2', ' {} {}', 1, 2)
58
test('{ a ', '{{ {0} ', 'a')
59
test('11', '{0}{0}', 1)
60
test('12', '{a}{b}', a=1, b=2)
61
test('12', '{a}{0}', 2, a=1)
62
test('1', '{0[0]}', [1])
63
test('1', '{0.a.b}', {'a':{'b':1}})
64
test('1', '{0[a][b]}', {'a':{'b':1}})
65
test('x', '{}', def (): return 'x';)
66
test('11', '{:b}', 3)
67
test('0b11', '{:#b}', 3)
68
test((30000).toLocaleString(), '{:,d}', 30000)
69
# in e.g. the indian number system, this is 3,00,000
70
test((300000).toLocaleString(), '{:,d}', 300000)
71
test('1.234568e+8', '{:e}', 123456789)
72
test('1.23E+8', '{:.2E}', 123456789)
73
test('12.35%', '{:.2%}', .123456789)
74
test((1234).toLocaleString(), '{:,}', 1234)
75
test('1_234', '{:_d}', 1234)
76
# 6 is the default: 1234.000000% or 1234,000000%
77
test((1234).toLocaleString(undefined, {'minimumFractionDigits': 6}), '{:,f}', 1234)
78
# 1234.0% or 1234,0%
79
test((1234).toLocaleString(undefined, {'minimumFractionDigits': 1}) + '%', '{:,.1%}', 12.34)
80
test((1234.57).toLocaleString(), '{:,g}', 1234.567)
81
test((1234).toLocaleString(), '{:,g}', 1234)
82
fnum = 1234
83
ae(f'{fnum:,}', (1234).toLocaleString())
84
test('left aligned ', '{:<30}', 'left aligned')
85
test(' right aligned', '{:>30}', 'right aligned')
86
test(' centered ', '{:^30}', 'centered')
87
test('***********centered***********', '{:*^30}', 'centered')
88
test('+3.140000; -3.140000', '{:+f}; {:+f}', 3.14, -3.14)
89
test('3.140000; -3.140000', '{:-f}; {:-f}', 3.14, -3.14)
90
test(' 3.140000; -3.140000', '{: f}; {: f}', 3.14, -3.14)
91
test('int: 42; hex: 2a; oct: 52; bin: 101010', "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42)
92
test('int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010', "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}", 42)
93
test('100', '{:{fill}{align}3}', 1, fill=0, align='<')
94
test_throws(AttributeError, '{0.a}', {})
95
test_throws(KeyError, '{a}', b=1)
96
test_throws(IndexError, '{} {}', 1)
97
test_throws(IndexError, '{1} {2}', 1)
98
test_throws(ValueError, '{1')
99
test_interpolation()
100
101
# Test miscellaneous services
102
ae('Abc', str.capitalize('aBC'))
103
ae(' 1 ', str.center('1', 3))
104
ae(2, str.count('xyx', 'x'))
105
ae(1, str.count('xyx', 'x', 2))
106
ae(True, str.endswith('a', ''))
107
ae(True, str.endswith('', ''))
108
ae(False, str.endswith('a', 'ab'))
109
ae(True, str.endswith('e', ['f', 'e']))
110
ae(True, str.startswith('a', ''))
111
ae(True, str.startswith('', ''))
112
ae(False, str.startswith('a', 'ab'))
113
ae(True, str.startswith('e', ['f', 'e']))
114
ae(1, str.find('ab', 'b'))
115
ae(2, str.rfind('abbc', 'b'))
116
ae(1, str.index('ab', 'b'))
117
ae(-1, str.find('abcd', 'b', 2))
118
ae(-1, str.find('abcd', 'b', 0, 1))
119
ae(-1, str.find('abcd', 'bcd', 0, 2))
120
ae(-1, str.rfind('abcd', 'b', 2))
121
ae(-1, str.rfind('abcd', 'b', 0, 1))
122
ae(3, str.rfind('abcd', 'd'))
123
ae('1,2', str.join(',', [1, 2]))
124
ae('1,2', str.join(',', iter([1, 2])))
125
ae('a ', str.ljust('a', 3))
126
ae(' a', str.rjust('a', 3))
127
ae('A', str.upper('a'))
128
ae('a', str.lower('A'))
129
ae('a', str.lstrip(' a'))
130
ae('a', str.lstrip('a'))
131
ae('a', str.rstrip('a '))
132
ae('a', str.rstrip('a'))
133
ae('a', str.strip(' a '))
134
ae('', str.strip(' '))
135
ae('', str.lstrip(' '))
136
ae('', str.rstrip(' '))
137
assrt.deepEqual(['1', ',', '2,3'], str.partition('1,2,3', ','))
138
assrt.deepEqual(['1,2,3', '', ''], str.partition('1,2,3', ' '))
139
assrt.deepEqual(['1,2', ',', '3'], str.rpartition('1,2,3', ','))
140
assrt.deepEqual(['', '', '1,2,3'], str.rpartition('1,2,3', ' '))
141
assrt.deepEqual(['1', ',2'], str.split('1,,2', ',', 1))
142
assrt.deepEqual(['1', '2', '3'], str.split('1 2 3'))
143
assrt.deepEqual(['1', '2 3'], str.split('1 2 3', None, 1))
144
assrt.deepEqual(['1', '2 \t3'], str.split('1 2 \t3', None, 1))
145
assrt.deepEqual(['-a--b-c', ''], str.rsplit('-a--b-c-', '-', 1))
146
assrt.deepEqual(['', 'a', 'b'], str.rsplit(',a,b', ','))
147
assrt.deepEqual([',a', 'b'], str.rsplit(',a,b', ',', 1))
148
assrt.deepEqual(['x,a', 'b'], str.rsplit('x,a,b', ',', 1))
149
assrt.deepEqual([' a b', 'c'], str.rsplit(' a b c ', None, 1))
150
assrt.deepEqual([' a bx', 'c'], str.rsplit(' a bx c ', None, 1))
151
for x in ['a\nb', 'a\r\nb', 'a\rb']:
152
assrt.deepEqual(['a', 'b'], str.splitlines(x))
153
assrt.deepEqual(['a', '', 'b'], str.splitlines('a\n\rb'))
154
assrt.deepEqual(['a\n', 'b'], str.splitlines('a\nb', True))
155
assrt.deepEqual(['a\r\n', 'b'], str.splitlines('a\r\nb', True))
156
ae('bbb', str.replace('aaa', 'a', 'b'))
157
ae('baa', str.replace('aaa', 'a', 'b', 1))
158
ae('bba', str.replace('aaa', 'a', 'b', 2))
159
ae('aaa', str.replace('aaa', 'a', 'a'))
160
ae('', str.replace('aaa', 'a', ''))
161
ae('a1B', str.swapcase('A1b'))
162
ae('001', str.zfill('1', 3))
163
ae('111', str.zfill('111', 2))
164
165
for f in (str, repr):
166
ae(f(True), 'True')
167
ae(f(False), 'False')
168
ae(f(None), 'None')
169
ae(f(1), '1')
170
ae(f([1,'2']), "[1, '2']")
171
ae(f({1:[1, '2']}), "{'1': [1, '2']}")
172
ae(f({1:'a', 2:'b'}), "{'1': 'a', '2': 'b'}")
173
ae(str('a'), 'a')
174
ae(repr('a'), "'a'")
175
176
bytes = list(range(256))
177
assrt.deepEqual(bytes, list(encodings.base64decode(encodings.base64encode(bytes))))
178
assrt.deepEqual(bytes, list(encodings.unhexlify(encodings.hexlify(bytes))))
179
for k in ['abc', "mūs", '', 's🐱a\u2028']:
180
bytes = encodings.utf8_encode(k)
181
ae(encodings.utf8_decode(bytes), k)
182
ae(encodings.utf8_decode(encodings.utf8_encode_js(k)), k)
183
assrt.deepEqual(list(bytes), list(encodings.base64decode(encodings.base64encode(bytes))))
184
185
from pythonize import strings
186
strings()
187
ae('{0} {a}'.format(1, a=2), str.format('{0} {a}', 1, a=2))
188
ae(' x '.strip(), str.strip(' x '))
189
ae(','.join([1,2,3]), str.join(',', [1,2,3]))
190
ae('11111'.count('1', start=1, end=1), str.count('11111', '1', start=1, end=1))
191
ae('{{}}'.format(), '{}')
192
ae('{x}}}'.format(x=1), '1}')
193
a = 1
194
ae(f'{{ {a} }}', '{ 1 }')
195
196