src/pylib/pystring/translate

Source   Edit  

str.translate


NOTE: Nim's KeyError is a subclass of ValueError instead of LookupError. Therefore when writing a custom TranslateTableABC or TypedTranslateTableABC for translate, beware a Nim's KeyError is not considered as a sign to leave such a character untouched, but will be just raised outside.

However, TranslateTable or StrTypedTranslateTable is handled via overload. Using them as translate table is fine.

Types

TranslateAction {.pure.} = enum
  skip, aOrd, aChr, aStr
Source   Edit  
TranslateTable = TableRef[int, TranslateTableVal]
result of maketrans Source   Edit  
TranslateTableABC = concept self
    self[int] is TranslateTableVal
Source   Edit  
TranslateTableVal = object
  case
  of skip:
    nil
  of aOrd:
    i*: int
  of aChr:
    c*: char
  of aStr:
    s*: PyStr
Source   Edit  
TranslateValType = int | PyStr | char | NoneType
Source   Edit  
TypedTranslateTableABC[V] = concept self
    V
    self[int] is V
Source   Edit  

Procs

func repr(table: TranslateTable): string {....raises: [], tags: [], forbids: [].}
dict stringification. Source   Edit  
proc translate(s: PyStr; table: StrTypedTranslateTable): PyStr {.
    ...raises: [TypeError], tags: [], forbids: [].}
Source   Edit  
proc translate(s: PyStr; table: TranslateTable): PyStr {.
    ...raises: [TypeError, ValueError, KeyError], tags: [], forbids: [].}
Source   Edit  
proc translate(s: PyStr; table: TranslateTableABC): PyStr
Source   Edit  

Macros

macro maketrans(_: typedesc[PyStr]; mapOrLit: untyped): TranslateTable
str.maketrans with dict literal or a mapping

Example:

let tbl = PyStr.maketrans({"a": None, "b": "123"})
assert "axb".translate(tbl) == "x123"
Source   Edit  

Templates

template `$`(table: TranslateTable): string
repr table Source   Edit  
template maketrans(_: typedesc[PyStr]; frm, to): StrTypedTranslateTable

frm, to shall be string/PyStr.

see Nim#23662 for why this is not defined as a proc with typed param-types

Source   Edit  
template maketrans(_: typedesc[PyStr]; frm, to, skip): TranslateTable

frm, to, skip shall be string/PyStr.

see Nim#23662 for why this is not defined as a proc with typed param-types

Source   Edit