Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit fde66e1

Browse files
committed
Fixed .capitalize() method of Unicode objects to work like the
corresponding string method. Added tests for this too. Patch written by Marc-Andre Lemburg. Copyright assigned to Guido van Rossum.
1 parent 30be870 commit fde66e1

3 files changed

Lines changed: 22 additions & 4 deletions

File tree

Lib/test/string_tests.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ def run_method_tests(test):
5353

5454
test('capitalize', ' hello ', ' hello ')
5555
test('capitalize', 'hello ', 'Hello ')
56+
test('capitalize', 'aaaa', 'Aaaa')
57+
test('capitalize', 'AaAa', 'Aaaa')
5658

5759
test('count', 'aaa', 3, 'a')
5860
test('count', 'aaa', 0, 'b')

Lib/test/test_unicode.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ def test(method, input, output, *args):
3131

3232
test('capitalize', u' hello ', u' hello ')
3333
test('capitalize', u'hello ', u'Hello ')
34+
test('capitalize', u'aaaa', u'Aaaa')
35+
test('capitalize', u'AaAa', u'Aaaa')
3436

3537
test('count', u'aaa', 3, u'a')
3638
test('count', u'aaa', 0, u'b')

Objects/unicodeobject.c

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2631,11 +2631,25 @@ int fixswapcase(PyUnicodeObject *self)
26312631
static
26322632
int fixcapitalize(PyUnicodeObject *self)
26332633
{
2634-
if (self->length > 0 && Py_UNICODE_ISLOWER(self->str[0])) {
2635-
self->str[0] = Py_UNICODE_TOUPPER(self->str[0]);
2636-
return 1;
2634+
int len = self->length;
2635+
Py_UNICODE *s = self->str;
2636+
int status = 0;
2637+
2638+
if (len == 0)
2639+
return 0;
2640+
if (Py_UNICODE_ISLOWER(*s)) {
2641+
*s = Py_UNICODE_TOUPPER(*s);
2642+
status = 1;
26372643
}
2638-
return 0;
2644+
s++;
2645+
while (--len > 0) {
2646+
if (Py_UNICODE_ISUPPER(*s)) {
2647+
*s = Py_UNICODE_TOLOWER(*s);
2648+
status = 1;
2649+
}
2650+
s++;
2651+
}
2652+
return status;
26392653
}
26402654

26412655
static

0 commit comments

Comments
 (0)