diff --git a/Lib/test/string_tests.py b/Lib/test/string_tests.py index 4b82d51b4508ac..a729b25cb680cd 100644 --- a/Lib/test/string_tests.py +++ b/Lib/test/string_tests.py @@ -1085,6 +1085,12 @@ def test_title(self): self.checkequal('Getint', "getInt", 'title') self.checkraises(TypeError, 'hello', 'title', 42) + def test_reverse(self): + self.checkequal('', '', 'reverse') + self.checkequal('Hello', 'olleH', 'reverse') + self.checkequal('Reversed this string', "gnirts siht desreveR", 'reverse') + self.checkraises(TypeError, 'hello', 'reverse', 42) + def test_splitlines(self): self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\rghi", 'splitlines') self.checkequal(['abc', 'def', '', 'ghi'], "abc\ndef\n\r\nghi", 'splitlines') diff --git a/Objects/clinic/unicodeobject.c.h b/Objects/clinic/unicodeobject.c.h index 99651f3c64bc5a..424ec5fe6c4e22 100644 --- a/Objects/clinic/unicodeobject.c.h +++ b/Objects/clinic/unicodeobject.c.h @@ -996,6 +996,26 @@ unicode_replace(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObjec return return_value; } +PyDoc_STRVAR(unicode_reverse__doc__, +"reverse($self, /)\n" +"--\n" +"\n" +"Return the reverse string.\n" +"\n" +"A string is reversed if all characters in the string are in reverse order."); + +#define UNICODE_REVERSE_METHODDEF \ + {"reverse", (PyCFunction)unicode_reverse, METH_NOARGS, unicode_reverse__doc__}, + +static PyObject * +unicode_reverse_impl(PyObject *self); + +static PyObject * +unicode_reverse(PyObject *self, PyObject *Py_UNUSED(ignored)) +{ + return unicode_reverse_impl(self); +} + PyDoc_STRVAR(unicode_removeprefix__doc__, "removeprefix($self, prefix, /)\n" "--\n" diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c index 03f15b37598363..9d79840a7f1044 100644 --- a/Objects/unicodeobject.c +++ b/Objects/unicodeobject.c @@ -11060,6 +11060,34 @@ replace(PyObject *self, PyObject *str1, return NULL; } +// asdf +static PyObject * +reverse(PyObject *string) +{ + if (ensure_unicode(string) < 0) + return NULL; + + Py_ssize_t length = PyUnicode_GET_LENGTH(string); + PyObject* reversed = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(string)); + + if (reversed == NULL) { + return NULL; + } + + for (Py_ssize_t i = 0; i < length; i++) { + Py_UCS4 ch = PyUnicode_READ_CHAR(string, length - 1 - i); + PyUnicode_WriteChar(reversed, i, ch); + } + + return reversed; +} + +static PyObject * +unicode_reverse_impl(PyObject *self) +{ + return reverse(self); +} + /* --- Unicode Object Methods --------------------------------------------- */ /*[clinic input]