Advertisement
shinemic

python-string-manipulation

Aug 22nd, 2021
1,376
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.75 KB | None | 0 0
  1. {
  2.  "cells": [
  3.   {
  4.    "cell_type": "markdown",
  5.    "id": "3f42a094",
  6.    "metadata": {},
  7.    "source": [
  8.     "### Python 中 `str.translate` 用法研究"
  9.    ]
  10.   },
  11.   {
  12.    "cell_type": "code",
  13.    "execution_count": 8,
  14.    "id": "490ff623",
  15.    "metadata": {},
  16.    "outputs": [
  17.     {
  18.      "name": "stdout",
  19.      "output_type": "stream",
  20.      "text": [
  21.       "Help on built-in function maketrans:\n",
  22.       "\n",
  23.       "maketrans(...)\n",
  24.       "    Return a translation table usable for str.translate().\n",
  25.       "    \n",
  26.       "    If there is only one argument, it must be a dictionary mapping Unicode\n",
  27.       "    ordinals (integers) or characters to Unicode ordinals, strings or None.\n",
  28.       "    Character keys will be then converted to ordinals.\n",
  29.       "    If there are two arguments, they must be strings of equal length, and\n",
  30.       "    in the resulting dictionary, each character in x will be mapped to the\n",
  31.       "    character at the same position in y. If there is a third argument, it\n",
  32.       "    must be a string, whose characters will be mapped to None in the result.\n",
  33.       "\n"
  34.      ]
  35.     }
  36.    ],
  37.    "source": [
  38.     "help(str.maketrans)"
  39.    ]
  40.   },
  41.   {
  42.    "cell_type": "markdown",
  43.    "id": "7237c5df",
  44.    "metadata": {},
  45.    "source": [
  46.     "* 使用 `str.maketrans` 方法作为 `str.translate` 传入参数。`str.maketrans` 方法可传入表示映射关系的字典,形式非常灵活"
  47.    ]
  48.   },
  49.   {
  50.    "cell_type": "code",
  51.    "execution_count": 9,
  52.    "id": "7efb51a8",
  53.    "metadata": {},
  54.    "outputs": [
  55.     {
  56.      "name": "stdout",
  57.      "output_type": "stream",
  58.      "text": [
  59.       "s     ==> |python|abc|\n",
  60.       "trans --> {97: 'x', 98: 'y', 99: 'z'} | after ==> |python|xyz| {97: 'x', 98: 'y', 99: 'z'}\n",
  61.       "trans --> {'a': 'x', 'b': 'y', 'c': 'z'} | after ==> |python|xyz| {97: 'x', 98: 'y', 99: 'z'}\n",
  62.       "trans --> {'a': 120, 'b': 121, 'c': 122} | after ==> |python|xyz| {97: 120, 98: 121, 99: 122}\n",
  63.       "trans --> {97: 120, 98: 121, 99: 122} | after ==> |python|xyz| {97: 120, 98: 121, 99: 122}\n",
  64.       "trans --> abc, xyz | after ==> |python|xyz| {97: 120, 98: 121, 99: 122}\n",
  65.       "trans --> abc, xyz, pyt | after ==> |hon|xyz| {97: 120, 98: 121, 99: 122, 112: None, 121: None, 116: None}\n"
  66.      ]
  67.     }
  68.    ],
  69.    "source": [
  70.     "maketrans_args = (\n",
  71.     "    (dict(zip(map(ord, 'abc'), 'xyz')), ),            # 单参数 -- 序号 => 字符\n",
  72.     "    (dict(zip('abc', 'xyz')), ),                      # 单参数 -- 字符 => 字符\n",
  73.     "    (dict(zip('abc', map(ord, 'xyz'))), ),            # 单参数 -- 字符 => 序号\n",
  74.     "    (dict(zip(map(ord, 'abc'), map(ord, 'xyz'))), ),  # 单参数 -- 序号 => 序号\n",
  75.     "    ('abc', 'xyz'),                                   # 双参数\n",
  76.     "    ('abc', 'xyz', 'pyt'),                            # 三参数 -- 最后一个参数表示这些字符映射成 None\n",
  77.     ")\n",
  78.     "\n",
  79.     "s = '|python|abc|'\n",
  80.     "print('s     ==>', s)\n",
  81.     "for trans in maketrans_args:\n",
  82.     "    trans_table = s.maketrans(*trans)\n",
  83.     "    print('trans -->', ', '.join(map(str, trans)), '|',\n",
  84.     "          'after ==>', s.translate(trans_table), trans_table)"
  85.    ]
  86.   },
  87.   {
  88.    "cell_type": "markdown",
  89.    "id": "2d1062de",
  90.    "metadata": {},
  91.    "source": [
  92.     "* 实现了 `__getitem__` 方法的对象:注意 `__getitem__` 传进来参数的类型为 `int`"
  93.    ]
  94.   },
  95.   {
  96.    "cell_type": "code",
  97.    "execution_count": 6,
  98.    "id": "bb34904a",
  99.    "metadata": {},
  100.    "outputs": [
  101.     {
  102.      "name": "stdout",
  103.      "output_type": "stream",
  104.      "text": [
  105.       "|python|abc| ==> ipobcd\n"
  106.      ]
  107.     }
  108.    ],
  109.    "source": [
  110.     "class Translator:\n",
  111.     "    def __init__(self, trans, drop=None):\n",
  112.     "        self.trans = trans\n",
  113.     "        self.drop = set(map(ord, drop)) if drop else []\n",
  114.     "\n",
  115.     "    def __getitem__(self, k):\n",
  116.     "        if k in self.drop:\n",
  117.     "            return None\n",
  118.     "        else:\n",
  119.     "            return k + 1\n",
  120.     "            # return chr(k + 1)\n",
  121.     "\n",
  122.     "    def __call__(self, s):\n",
  123.     "        return s.translate(self)\n",
  124.     "\n",
  125.     "\n",
  126.     "print('|python|abc|', '==>', '|python|abc|'.translate(Translator('abc', 'pyt|')))"
  127.    ]
  128.   }
  129.  ],
  130.  "metadata": {
  131.   "kernelspec": {
  132.    "display_name": "Python 3 (ipykernel)",
  133.    "language": "python",
  134.    "name": "python3"
  135.   },
  136.   "language_info": {
  137.    "codemirror_mode": {
  138.     "name": "ipython",
  139.     "version": 3
  140.    },
  141.    "file_extension": ".py",
  142.    "mimetype": "text/x-python",
  143.    "name": "python",
  144.    "nbconvert_exporter": "python",
  145.    "pygments_lexer": "ipython3",
  146.    "version": "3.8.11"
  147.   }
  148.  },
  149.  "nbformat": 4,
  150.  "nbformat_minor": 5
  151. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement