英文:
Replace all superscript digits with one `re.sub`
问题
Here's the translated code portion:
import re
content = "m^2 s^3"
content = re.sub(r"\^0", "\N{Superscript Zero}", content)
content = re.sub(r"\^1", "\N{Superscript One}", content)
content = re.sub(r"\^2", "\N{Superscript Two}", content)
content = re.sub(r"\^3", "\N{Superscript Three}", content)
content = re.sub(r"\^4", "\N{Superscript Four}", content)
content = re.sub(r"\^5", "\N{Superscript Five}", content)
content = re.sub(r"\^6", "\N{Superscript Six}", content)
content = re.sub(r"\^7", "\N{Superscript Seven}", content)
content = re.sub(r"\^8", "\N{Superscript Eight}", content)
content = re.sub(r"\^9", "\N{Superscript Nine}", content)
print(content)
Please note that this code is for replacing exponents in a given string with their Unicode equivalents using Python.
英文:
Given a string with exponents like ^2
in it, I'd like to replace them with their unicode equivalents using Python.
This works:
import re
content = "m^2 s^3"
content = re.sub(r"\^0", "\N{Superscript Zero}", content)
content = re.sub(r"\^1", "\N{Superscript One}", content)
content = re.sub(r"\^2", "\N{Superscript Two}", content)
content = re.sub(r"\^3", "\N{Superscript Three}", content)
content = re.sub(r"\^4", "\N{Superscript Four}", content)
content = re.sub(r"\^5", "\N{Superscript Five}", content)
content = re.sub(r"\^6", "\N{Superscript Six}", content)
content = re.sub(r"\^7", "\N{Superscript Seven}", content)
content = re.sub(r"\^8", "\N{Superscript Eight}", content)
content = re.sub(r"\^9", "\N{Superscript Nine}", content)
print(content)
but I feel this repetition (or loop equivalent) can't be too efficient. Is there a way to solve the problem with one re.sub
?
答案1
得分: 2
你可以在 re.sub 中使用 lambda 进行替换。这将允许你使用字典或翻译表将数字映射到它们的上标版本。
import re
toSuper = str.maketrans("0123456789","⁰¹²³⁴⁵⁶⁷⁸⁹")
content = "m^2 s^3 x^59"
content = re.sub(r"\^([0-9]+)",lambda m:m.group(1).translate(toSuper),content)
print(content)
m² s³ x⁵⁹
英文:
You can use a lambda for the replacement in re.sub. This will allow you to use a dictionary or translation table to map the numbers to their superscript versions.
import re
toSuper = str.maketrans("0123456789","⁰¹²³⁴⁵⁶⁷⁸⁹")
content = "m^2 s^3 x^59"
content = re.sub(r"\^([0-9]+)",lambda m:m.group(1).translate(toSuper),content)
print(content)
m² s³ x⁵⁹
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论