RosettaCodeData/Task/Reverse-a-string/Python/reverse-a-string-4.py

30 lines
957 B
Python
Raw Permalink Normal View History

2016-12-05 22:15:40 +01:00
import unicodedata
def ureverse(ustring):
2019-09-12 10:33:56 -07:00
'Reverse a string including unicode combining characters'
2016-12-05 22:15:40 +01:00
groupedchars = []
uchar = list(ustring)
while uchar:
2019-09-12 10:33:56 -07:00
if unicodedata.combining(uchar[0]) != 0:
2016-12-05 22:15:40 +01:00
groupedchars[-1] += uchar.pop(0)
else:
groupedchars.append(uchar.pop(0))
# Grouped reversal
groupedchars = groupedchars[::-1]
return ''.join(groupedchars)
2019-09-12 10:33:56 -07:00
def say_string(s):
return ' '.join([s, '=', ' | '.join(unicodedata.name(ch, '') for ch in s)])
def say_rev(s):
print(f"Input: {say_string(s)}")
print(f"Character reversed: {say_string(s[::-1])}")
print(f"Unicode reversed: {say_string(ureverse(s))}")
print(f"Unicode reverse²: {say_string(ureverse(ureverse(s)))}")
2016-12-05 22:15:40 +01:00
if __name__ == '__main__':
2019-09-12 10:33:56 -07:00
ucode = ''.join(chr(int(n[2:], 16)) for n in
'U+0041 U+030A U+0073 U+0074 U+0072 U+006F U+0308 U+006D'.split())
say_rev(ucode)