用一个 `re.sub` 替换所有上标数字。

huangapple go评论63阅读模式
英文:

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⁵⁹

huangapple
  • 本文由 发表于 2023年5月13日 21:49:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76243065.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定