Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Capture first letter of duplicate

So, I’ve been trying to create a program that converts from romaji (romanization of japanese) to the hiragana alphabet. I would like to match the first letters of ‘kk’, ‘ss’, ‘tt’, and ‘pp’.

My attempt:

re.sub(r'(?=([kstp]))\1', 'っ', string)

I expect 'tooka' to output 'tooka' and 'yokka' should output 'yoっka', but my regex appears to just be matching [kstp].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there an easy way I can fix this?

>Solution :

You put positive-lookahead (?=...) in the wrong position. Try:

import re

lst = ['tooka', 'yokka', 'chotto', 'koppu']
print([re.sub(r'([kstp])(?=\1)', 'っ', s) for s in lst])
# ['tooka', 'yoっka', 'choっto', 'koっpu']

Or a simpler one re.sub(r'([kstp])\1', r'っ\1', s) works too.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading