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

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

Replace all superscript digits with one `re.sub`

问题

Here's the translated code portion:

  1. import re
  2. content = "m^2 s^3"
  3. content = re.sub(r"\^0", "\N{Superscript Zero}", content)
  4. content = re.sub(r"\^1", "\N{Superscript One}", content)
  5. content = re.sub(r"\^2", "\N{Superscript Two}", content)
  6. content = re.sub(r"\^3", "\N{Superscript Three}", content)
  7. content = re.sub(r"\^4", "\N{Superscript Four}", content)
  8. content = re.sub(r"\^5", "\N{Superscript Five}", content)
  9. content = re.sub(r"\^6", "\N{Superscript Six}", content)
  10. content = re.sub(r"\^7", "\N{Superscript Seven}", content)
  11. content = re.sub(r"\^8", "\N{Superscript Eight}", content)
  12. content = re.sub(r"\^9", "\N{Superscript Nine}", content)
  13. 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:

  1. import re
  2. content = "m^2 s^3"
  3. content = re.sub(r"\^0", "\N{Superscript Zero}", content)
  4. content = re.sub(r"\^1", "\N{Superscript One}", content)
  5. content = re.sub(r"\^2", "\N{Superscript Two}", content)
  6. content = re.sub(r"\^3", "\N{Superscript Three}", content)
  7. content = re.sub(r"\^4", "\N{Superscript Four}", content)
  8. content = re.sub(r"\^5", "\N{Superscript Five}", content)
  9. content = re.sub(r"\^6", "\N{Superscript Six}", content)
  10. content = re.sub(r"\^7", "\N{Superscript Seven}", content)
  11. content = re.sub(r"\^8", "\N{Superscript Eight}", content)
  12. content = re.sub(r"\^9", "\N{Superscript Nine}", content)
  13. 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 进行替换。这将允许你使用字典或翻译表将数字映射到它们的上标版本。

  1. import re
  2. toSuper = str.maketrans("0123456789","⁰¹²³⁴⁵⁶⁷⁸⁹")
  3. content = "m^2 s^3 x^59"
  4. content = re.sub(r"\^([0-9]+)",lambda m:m.group(1).translate(toSuper),content)
  5. print(content)
  6. 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.

  1. import re
  2. toSuper = str.maketrans("0123456789","⁰¹²³⁴⁵⁶⁷⁸⁹")
  3. content = "m^2 s^3 x^59"
  4. content = re.sub(r"\^([0-9]+)",lambda m:m.group(1).translate(toSuper),content)
  5. print(content)
  6. 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:

确定