{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## 字符串操作" ] }, { "cell_type": "markdown", "metadata": { "jp-MarkdownHeadingCollapsed": true, "tags": [] }, "source": [ "标准**序列操作**适用于字符串\n", "\n", "- 索引,分片\n", "- 乘法,加法\n", "- 成员资格判断\n", "- 求长度,最大值,最小值\n", "\n", "字符串**不可变**,因此**分片赋值**或**单独赋值**是不合法的" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "在某种程度上,可以把字符串看做一个字符列表" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "下列示例字符串选自由孙燕姿演唱的歌曲《我怀念的》,姚若龙 作词,戳我观看MV\n", "\n", "\n", "\n", "我怀念的是无话不说\n", "\n", "我怀念的是一起作梦\n", "\n", "我怀念的是争吵以后\n", "\n", "还是想要爱你的冲动" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "下列示例字符串选自由伍佰&杨乃文演唱的歌曲《最初的地方》,余光中 作词,戳我观看现场视频\n", "\n", "回到最初我们来的地方\n", "\n", "好多的天真被我们遗忘\n", "\n", "你说过快乐就在这路上\n", "\n", "从不在乎结果究竟会怎样" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "lyrics_1 = \"我怀念的是无话不说\"" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'念'" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 按索引访问\n", "lyrics_1[2]" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'无话不说'" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 分片\n", "lyrics_1[-4:]" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 成员判断\n", "'我' in lyrics_1" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 成员判断\n", "'无话不说' in lyrics_1" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'说不话无是的念怀我'" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 倒序\n", "lyrics_1[::-1]" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'我怀念的是无话不说我怀念的是无话不说'" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 乘法\n", "\n", "lyrics_1 * 2" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'我怀念的是无话不说,我怀念的是一起作梦'" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 加法\n", "\n", "lyrics_1 + ',' +\"我怀念的是一起作梦\"" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'我怀念的,我怀念的,是无话不说'" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 重复和扩展(乘法和加法)\n", "\n", "'我怀念的,' * 2 + '是无话不说'" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "9" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 求长度\n", "\n", "len(lyrics_1)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'说'" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 最大值\n", "\n", "max(lyrics_1)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'不'" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 最小值\n", "\n", "min(lyrics_1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "思考题:请**用代码**解释`max(lyrics_1)`和`min(lyrics_1)`的执行过程" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "# 字符串不可变,单独赋值不行,不行,不行\n", "# lyrics_1[0] = '你'" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "# 字符串不可变,切片赋值不行,不行,不行\n", "# lyrics_1[1:3] = '想念' " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 字符串常用方法" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "先用内置函数`help`查看一下字符串的所有方法:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'go on '" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"My heart will go on and on\"[14:20]" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "str1 = '喜欢看你紧紧皱眉 叫我胆小鬼'" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'胆小鬼'" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str1[-3:15]" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "# help(str)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "接下来咱们看看有哪些常用方法:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "方法`center`通过在**两边**添加填充字符(默认为空格)让字符串**居中**" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' 回到最初我们来的地方 '" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"回到最初我们来的地方\".center(20)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'~~~~~回到最初我们来的地方~~~~~'" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"回到最初我们来的地方\".center(20,'~')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "方法`find`在字符串中查找子串。如果找到,就**返回**子串的**第一个字符的索引**,否则返回-1。" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"回到最初我们来的地方\".find('我们')" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'我'" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"回到最初我们来的地方\"[4]" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "17" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 返回第一次出现时的索引值,即使多次出现了\n", "\"My heart will go on and on\".find('on')" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "17" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 指定查找的范围,即子串[14:20],返回结果为17,这个结果的索引是在整个字符串中的索引,而不是在子串中的索引\n", "\"My heart will go on and on\".find('on',14,20)" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "9" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"My heart will go on and on\".find('wi')" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-1" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"My heart will go on and on\".find('wi',14,20)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'o'" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"My heart will go on and on\"[17]" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "26" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(\"My heart will go on and on\")" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'o'" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"My heart will go on and on\"[24]" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-1" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 没找到,返回-1\n", "\"My heart will go on and on\".find('you')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "以下歌词来自《My Heart Will Go On》,由Will Jennings作词,戳我观看MV\n", "\n", "```\n", "Every night in my dreams\n", "I see you, I feel you,\n", "That is how I know you go on\n", "\n", "Far across the distance\n", "And spaces between us\n", "You have come to show you go on\n", "\n", "Near, far, wherever you are\n", "I believe that the heart does go on\n", "Once more you open the door\n", "And you are here in my heart\n", "And my heart will go on and on\n", "\n", "Love can touch us one time\n", "And last for a lifetime\n", "And never let go till we are gone\n", "\n", "Love was when I loved you\n", "One true time I hold to\n", "In my life we will always go on\n", "\n", "Near, far, wherever you are\n", "I believe that the heart does go on\n", "Once more you open the door\n", "And you are here in my heart\n", "And my heart will go on and on\n", "\n", "You are here, there is nothing I fear,\n", "And I know that my heart will go on\n", "We will stay forever this way\n", "You are safe in my heart\n", "And my heart will go on and on\n", "```" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "lyrics = '''Every night in my dreams\n", "I see you, I feel you,\n", "That is how I know you go on\n", "\n", "Far across the distance\n", "And spaces between us\n", "You have come to show you go on\n", "\n", "Near, far, wherever you are\n", "I believe that the heart does go on\n", "Once more you open the door\n", "And you are here in my heart\n", "And my heart will go on and on\n", "\n", "Love can touch us one time\n", "And last for a lifetime\n", "And never let go till we are gone\n", "\n", "Love was when I loved you\n", "One true time I hold to\n", "In my life we will always go on\n", "\n", "Near, far, wherever you are\n", "I believe that the heart does go on\n", "Once more you open the door\n", "And you are here in my heart\n", "And my heart will go on and on\n", "\n", "You are here, there is nothing I fear,\n", "And I know that my heart will go on\n", "We will stay forever this way\n", "You are safe in my heart\n", "And my heart will go on and on'''" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Every night in my dreams\\nI see you, I feel you,\\nThat is how I know you go on\\n\\nFar across the distance\\nAnd spaces between us\\nYou have come to show you go on\\n\\nNear, far, wherever you are\\nI believe that the heart does go on\\nOnce more you open the door\\nAnd you are here in my heart\\nAnd my heart will go on and on\\n\\nLove can touch us one time\\nAnd last for a lifetime\\nAnd never let go till we are gone\\n\\nLove was when I loved you\\nOne true time I hold to\\nIn my life we will always go on\\n\\nNear, far, wherever you are\\nI believe that the heart does go on\\nOnce more you open the door\\nAnd you are here in my heart\\nAnd my heart will go on and on\\n\\nYou are here, there is nothing I fear,\\nAnd I know that my heart will go on\\nWe will stay forever this way\\nYou are safe in my heart\\nAnd my heart will go on and on'" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lyrics" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Every night in my dreams I see you, I feel you, That is how I know you go on Far across the distance And spaces between us You have come to show you go on Near, far, wherever you are I believe that the heart does go on Once more you open the door And you are here in my heart And my heart will go on and on Love can touch us one time And last for a lifetime And never let go till we are gone Love was when I loved you One true time I hold to In my life we will always go on Near, far, wherever you are I believe that the heart does go on Once more you open the door And you are here in my heart And my heart will go on and on You are here, there is nothing I fear, And I know that my heart will go on We will stay forever this way You are safe in my heart And my heart will go on and on'" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 把换行符\\n替换为空格\n", "lyrics.replace('\\n',' ')" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [], "source": [ "lyrics_str = lyrics.replace('\\n',' ')" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [], "source": [ "# 使用split函数把歌词字符串转换为单词列表\n", "lyrics_list = lyrics_str.split(' ')" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Every', 'night', 'in', 'my', 'dreams', 'I', 'see', 'you,', 'I', 'feel', 'you,', 'That', 'is', 'how', 'I', 'know', 'you', 'go', 'on', '', 'Far', 'across', 'the', 'distance', 'And', 'spaces', 'between', 'us', 'You', 'have', 'come', 'to', 'show', 'you', 'go', 'on', '', 'Near,', 'far,', 'wherever', 'you', 'are', 'I', 'believe', 'that', 'the', 'heart', 'does', 'go', 'on', 'Once', 'more', 'you', 'open', 'the', 'door', 'And', 'you', 'are', 'here', 'in', 'my', 'heart', 'And', 'my', 'heart', 'will', 'go', 'on', 'and', 'on', '', 'Love', 'can', 'touch', 'us', 'one', 'time', 'And', 'last', 'for', 'a', 'lifetime', 'And', 'never', 'let', 'go', 'till', 'we', 'are', 'gone', '', 'Love', 'was', 'when', 'I', 'loved', 'you', 'One', 'true', 'time', 'I', 'hold', 'to', 'In', 'my', 'life', 'we', 'will', 'always', 'go', 'on', '', 'Near,', 'far,', 'wherever', 'you', 'are', 'I', 'believe', 'that', 'the', 'heart', 'does', 'go', 'on', 'Once', 'more', 'you', 'open', 'the', 'door', 'And', 'you', 'are', 'here', 'in', 'my', 'heart', 'And', 'my', 'heart', 'will', 'go', 'on', 'and', 'on', '', 'You', 'are', 'here,', 'there', 'is', 'nothing', 'I', 'fear,', 'And', 'I', 'know', 'that', 'my', 'heart', 'will', 'go', 'on', 'We', 'will', 'stay', 'forever', 'this', 'way', 'You', 'are', 'safe', 'in', 'my', 'heart', 'And', 'my', 'heart', 'will', 'go', 'on', 'and', 'on']\n" ] } ], "source": [ "print(lyrics_list)" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Every night in my dreams I see you, I feel you, That is how I know you go on Far across the distance And spaces between us You have come to show you go on Near, far, wherever you are I believe that the heart does go on Once more you open the door And you are here in my heart And my heart will go on and on Love can touch us one time And last for a lifetime And never let go till we are gone Love was when I loved you One true time I hold to In my life we will always go on Near, far, wherever you are I believe that the heart does go on Once more you open the door And you are here in my heart And my heart will go on and on You are here, there is nothing I fear, And I know that my heart will go on We will stay forever this way You are safe in my heart And my heart will go on and on'" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 使用join函数将列表合并为字符串\n", "' '.join(lyrics_list)" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Every night in my dreams I see you, I feel you, That is how I know you go on Far across the distance And spaces between us You have come to show you go on Near, far, wherever you are I believe that the heart does go on Once more you open the door And you are here in my heart And my heart will go on and on Love can touch us one time And last for a lifetime And never let go till we are gone Love was when I loved you One true time I hold to In my life we will always go on Near, far, wherever you are I believe that the heart does go on Once more you open the door And you are here in my heart And my heart will go on and on You are here, there is nothing I fear, And I know that my heart will go on We will stay forever this way You are safe in my heart And my heart will go on and on'" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lyrics_str" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['My', 'heart', 'will', 'go', 'on', 'and', 'on']" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"My heart will go on and on\".split(' ')" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'My~heart~will~go~on~and~on'" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'~'.join(['My', 'heart', 'will', 'go', 'on', 'and', 'on'])" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [], "source": [ "num_str = '1 2 \\r 3\\t4\\n9'" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "num_list = num_str.split()" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['1', '2', '3', '4', '9']" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "num_list" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'1*2*3*4*9'" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'*'.join(num_list)" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1*2*3*4*9的计算结果为:216\n" ] } ], "source": [ "print(f\"{'*'.join(num_list)}的计算结果为:{1*2*3*4*9}\")" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'every night in my dreams i see you, i feel you, that is how i know you go on far across the distance and spaces between us you have come to show you go on near, far, wherever you are i believe that the heart does go on once more you open the door and you are here in my heart and my heart will go on and on love can touch us one time and last for a lifetime and never let go till we are gone love was when i loved you one true time i hold to in my life we will always go on near, far, wherever you are i believe that the heart does go on once more you open the door and you are here in my heart and my heart will go on and on you are here, there is nothing i fear, and i know that my heart will go on we will stay forever this way you are safe in my heart and my heart will go on and on'" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 使用lower函数将字符串全部,全部,全部,变为小写,小写,小写\n", "lyrics_str.lower()" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'EVERY NIGHT IN MY DREAMS I SEE YOU, I FEEL YOU, THAT IS HOW I KNOW YOU GO ON FAR ACROSS THE DISTANCE AND SPACES BETWEEN US YOU HAVE COME TO SHOW YOU GO ON NEAR, FAR, WHEREVER YOU ARE I BELIEVE THAT THE HEART DOES GO ON ONCE MORE YOU OPEN THE DOOR AND YOU ARE HERE IN MY HEART AND MY HEART WILL GO ON AND ON LOVE CAN TOUCH US ONE TIME AND LAST FOR A LIFETIME AND NEVER LET GO TILL WE ARE GONE LOVE WAS WHEN I LOVED YOU ONE TRUE TIME I HOLD TO IN MY LIFE WE WILL ALWAYS GO ON NEAR, FAR, WHEREVER YOU ARE I BELIEVE THAT THE HEART DOES GO ON ONCE MORE YOU OPEN THE DOOR AND YOU ARE HERE IN MY HEART AND MY HEART WILL GO ON AND ON YOU ARE HERE, THERE IS NOTHING I FEAR, AND I KNOW THAT MY HEART WILL GO ON WE WILL STAY FOREVER THIS WAY YOU ARE SAFE IN MY HEART AND MY HEART WILL GO ON AND ON'" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 使用upper函数将字符串全部,全部,全部,变为大写,大写,大写\n", "lyrics_str.upper()" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [], "source": [ "lyrics_lower = lyrics_str.lower()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "方法`replace`将指定子串都替换为另一个字符串,并返回替换后的结果。类似的`translate`方法参考教材练习一下。" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [], "source": [ "# 贾岛骑驴作诗,最开始想到的词句是\n", "poems = '鸟宿池边树,僧推月下门'" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [], "source": [ "# 一边骑驴一边琢磨,敲字好像不合适,换个什么字好呢" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [], "source": [ "# 思索的时候,骑驴分神,撞到了时任京兆尹的韩愈的出巡队伍里" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [], "source": [ "# 韩愈了解情况后,说,我来给你替换一下,于是便有了下一行代码" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'鸟宿池边树,僧敲月下门'" ] }, "execution_count": 53, "metadata": {}, "output_type": "execute_result" } ], "source": [ "poems.replace('推','敲')" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'good'" ] }, "execution_count": 54, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'goooood'.replace('ooo','')" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'s~ g~~d'" ] }, "execution_count": 55, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'so good'.replace('o','~')" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'鸟宿池边树,僧推月下门'" ] }, "execution_count": 56, "metadata": {}, "output_type": "execute_result" } ], "source": [ "poems" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "方法`strip`将字符串**开头和末尾**的空白(但不包括中间的空白)删除,并返回删除后的结果。" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [], "source": [ "str_6 = ' 首行缩进2个字符。\\r\\n我是第二行\\n我是第\\t三行。终于写完了,使劲敲下回车\\r\\n'" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 首行缩进2个字符。\n", "我是第二行\n", "我是第\t三行。终于写完了,使劲敲下回车\n", "\n" ] } ], "source": [ "print(str_6)" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'首行缩进2个字符。\\r\\n我是第二行\\n我是第\\t三行。终于写完了,使劲敲下回车'" ] }, "execution_count": 59, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str_6.strip()" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' 首行缩进2个字符。\\r\\n我是第二行\\n我是第\\t三行。终于写完了,使劲敲下回车\\r\\n'" ] }, "execution_count": 60, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str_6" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [], "source": [ "str_7 = ' 首行缩进2个字符。\\r\\n我是第二行\\n我是第\\t三行。终于写完了,使劲敲下回车\\t\\r\\n'" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'首行缩进2个字符。\\r\\n我是第二行\\n我是第\\t三行。终于写完了,使劲敲下回车'" ] }, "execution_count": 62, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str_7.strip()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "空白包含`\\n`,`\\r`,`\\t`,` `,不知包括空格哦 (~ ̄▽ ̄~)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "还可以使用strip删除字符串首尾的指定的(一个或者多个)字符" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [], "source": [ "str_8 = 'ababoabcll'" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'ababoabc'" ] }, "execution_count": 64, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str_8.strip('l')" ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'ababoabcll'" ] }, "execution_count": 65, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str_8" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'oabcll'" ] }, "execution_count": 66, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str_8.strip('ab')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`startswith`和`endswith`函数用来判断字符串首尾是否以特定字符(串)开始或结束" ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 67, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str_8.startswith('a')" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str_8.startswith('ab')" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 69, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str_8.startswith('aba')" ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 70, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str_8.endswith('l')" ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 71, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 指定字符串子串的首尾索引值,可以用来对子串进行首尾字符判断\n", "str_8.endswith('l', 0, 5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`index`函数返回指定字符(串)在字符串中的第一次出现,第一次出现,第一次出现的索引值" ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 72, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str_8.index('a')" ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [], "source": [ "# 如果没找到,就会报错哦 (╬▔^▔)凸\n", "# str_8.index('bcd')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`count`函数用来计算指定字符(串)在字符串中出现的次数,这个函数很重要,一定要会灵活使用哦,[>\\\\/<] " ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [], "source": [ "# 看看下面这段绕口令里出现几次 扁担,几次 板凳\n", "rao_str = '扁担长,板凳宽,板凳没有扁担长,扁担没有板凳宽。扁担要绑在板凳上,板凳偏不让扁担绑在板凳上。'" ] }, { "cell_type": "code", "execution_count": 75, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 75, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rao_str.count('扁担')" ] }, { "cell_type": "code", "execution_count": 76, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 76, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rao_str.count('板凳')" ] }, { "cell_type": "code", "execution_count": 77, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "th3s 3s str3ng 2x1mpl2....w4w!!!\n" ] } ], "source": [ "intab = \"aeiou\"\n", "outtab = \"12345\"\n", "trantab = str.maketrans(intab, outtab) \n", "\n", "str10 = \"this is string example....wow!!!\"\n", "print (str10.translate(trantab)) # th3s 3s str3ng 2x1mpl2....w4w!!!" ] }, { "cell_type": "code", "execution_count": 78, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "不坏\n" ] } ], "source": [ "intab = \"好\"\n", "outtab = \"坏\"\n", "trantab = str.maketrans(intab, outtab) \n", "\n", "str10 = \"不好\"\n", "print (str10.translate(trantab)) # th3s 3s str3ng 2x1mpl2....w4w!!!" ] }, { "cell_type": "code", "execution_count": 79, "metadata": {}, "outputs": [], "source": [ "# help(str.translate)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "使用字符串的下列`方法`判断字符串是否满足特定的条件:`isalnum`、`isalpha`、`isdecimal`、`isdigit`、`isidentifier`、`islower`、`isnumeric`、`isprintable`、`isspace`、`istitle、isupper`。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "使用字符串的下列方法判断字符串是否满足特定的条件:isalnum、isalpha、isdecimal、isdigit、isidentifier、islower、isnumeric、isprintable、isspace、istitle、isupper字符串的方法很多,自己一定,一定,一定多练习敲代码哦" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "string模块包含了许多常用字符集\n", "\n", "下面是模块string中几个很有用的常量:\n", "\n", "- `string.digits`:包含数字0~9的字符串。\n", "- `string.ascii_letters`:包含所有ASCII字母(大写和小写)的字符串。\n", "- `string.ascii_lowercase`:包含所有小写ASCII字母的字符串。\n", "- `string.printable`:包含所有可打印的ASCII字符的字符串。\n", "- `string.punctuation`:包含所有ASCII标点字符的字符串。\n", "- `string.ascii_uppercase`:包含所有大写ASCII字母的字符串。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "使用`string`模块中的这些字符集时,一定要,一定要,一定要,先导入string模块" ] }, { "cell_type": "code", "execution_count": 80, "metadata": {}, "outputs": [], "source": [ "import string" ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [], "source": [ "# help(string)" ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'0123456789'" ] }, "execution_count": 82, "metadata": {}, "output_type": "execute_result" } ], "source": [ "string.digits" ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~'" ] }, "execution_count": 83, "metadata": {}, "output_type": "execute_result" } ], "source": [ "string.punctuation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "思考题:分析《My Heart Will Go On》的歌词中出现频率最高的5个词语,系动词和标点不算。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**string模块**\n", "\n", "下面是模块string中几个很有用的常量:\n", "\n", "- `string.digits`:包含数字0~9的字符串。\n", "- `string.ascii_letters`:包含所有ASCII字母(大写和小写)的字符串。\n", "- `string.ascii_lowercase`:包含所有小写ASCII字母的字符串。\n", "- `string.printable`:包含所有可打印的ASCII字符的字符串。\n", "- `string.punctuation`:包含所有ASCII标点字符的字符串。\n", "- `string.ascii_uppercase`:包含所有大写ASCII字母的字符串。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "使用`string`模块中的这些字符集时,一定要,一定要,一定要,先导入string模块" ] }, { "cell_type": "code", "execution_count": 84, "metadata": {}, "outputs": [], "source": [ "import string" ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'0123456789'" ] }, "execution_count": 85, "metadata": {}, "output_type": "execute_result" } ], "source": [ "string.digits" ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~'" ] }, "execution_count": 86, "metadata": {}, "output_type": "execute_result" } ], "source": [ "string.punctuation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 常用的处理字符串的内置函数" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- `str()`函数:将值转化为适于人阅读的**字符串**的形式;\n", "\n", "- `repr()`函数:将值转化为供解释器读取的**字符串**形式;\n", "\n", "- `eval()`函数:执行一个字符串表达式,并返回表达式的值。\n", "\n", "拓展学习python3编程基础:str()、repr()的区别" ] }, { "cell_type": "code", "execution_count": 87, "metadata": {}, "outputs": [], "source": [ "x = 123" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [], "source": [ "x_str = str(x)" ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'123'" ] }, "execution_count": 89, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x_str" ] }, { "cell_type": "code", "execution_count": 90, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 90, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(x_str)" ] }, { "cell_type": "code", "execution_count": 91, "metadata": {}, "outputs": [], "source": [ "x_repr = repr(x)" ] }, { "cell_type": "code", "execution_count": 92, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'123'" ] }, "execution_count": 92, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x_repr" ] }, { "cell_type": "code", "execution_count": 93, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 93, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(x_repr)" ] }, { "cell_type": "code", "execution_count": 94, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "123" ] }, "execution_count": 94, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 执行一个字符串表达式\n", "eval(x_str)" ] }, { "cell_type": "code", "execution_count": 95, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "123" ] }, "execution_count": 95, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 执行一个字符串表达式\n", "eval(x_repr)" ] }, { "cell_type": "code", "execution_count": 96, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 96, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(eval(x_str))" ] }, { "cell_type": "code", "execution_count": 97, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 97, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(eval(x_repr))" ] }, { "cell_type": "code", "execution_count": 98, "metadata": {}, "outputs": [], "source": [ "y = '123'" ] }, { "cell_type": "code", "execution_count": 99, "metadata": {}, "outputs": [], "source": [ "y_str = str(y)" ] }, { "cell_type": "code", "execution_count": 100, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'123'" ] }, "execution_count": 100, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y_str" ] }, { "cell_type": "code", "execution_count": 101, "metadata": {}, "outputs": [], "source": [ "y_repr = repr(y)" ] }, { "cell_type": "code", "execution_count": 102, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "\"'123'\"" ] }, "execution_count": 102, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y_repr" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`str()`和`repr()`都可以把出传入的对象转换为字符串,当传入对象为字符串类型时,`repr()`会再加一层引号;\n", "\n", "`eval()`函数接收**字符串**,先把字符串的**引号去掉**,再把字符串引号里的内容当做表达式执行,并返回执行结果。" ] }, { "cell_type": "code", "execution_count": 103, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 103, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(eval(y_repr))" ] }, { "cell_type": "code", "execution_count": 104, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 104, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(eval(y_str))" ] }, { "cell_type": "code", "execution_count": 105, "metadata": {}, "outputs": [], "source": [ "exp_1 = '+'.join('1234')" ] }, { "cell_type": "code", "execution_count": 106, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'1+2+3+4'" ] }, "execution_count": 106, "metadata": {}, "output_type": "execute_result" } ], "source": [ "exp_1" ] }, { "cell_type": "code", "execution_count": 107, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 107, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(exp_1)" ] }, { "cell_type": "code", "execution_count": 108, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'1+2+3+4'" ] }, "execution_count": 108, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str(exp_1)" ] }, { "cell_type": "code", "execution_count": 109, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"'1+2+3+4'\"" ] }, "execution_count": 109, "metadata": {}, "output_type": "execute_result" } ], "source": [ "repr(exp_1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "思考题:\n", "\n", " - 如果下面运行代码`eval(str(exp_1))`,结果是什么\n", " - 如果下面运行代码`eval(repr(exp_1))`,结果是什么" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 转义字符" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "有些字符**无法直接输出**,可以通过`\\`转义**其它字符**实现。你可以把下表理解为,在Python中表示**特殊字符**的汇总表。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "\n", "

转义字符表

\n", "
" ] }, { "cell_type": "code", "execution_count": 110, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "line1\n", "line2\n", "line3\n" ] } ], "source": [ "print('''line1\n", "line2\n", "line3''')" ] }, { "cell_type": "code", "execution_count": 111, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "line1line2line3\n" ] } ], "source": [ "print('''line1\\\n", "line2\\\n", "line3''')" ] }, { "cell_type": "code", "execution_count": 112, "metadata": {}, "outputs": [], "source": [ "# 这样无法输出\\\n", "# print('\\')" ] }, { "cell_type": "code", "execution_count": 113, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\\\n" ] } ], "source": [ "print('\\\\')" ] }, { "cell_type": "code", "execution_count": 114, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "'\n" ] } ], "source": [ "print(\"'\")" ] }, { "cell_type": "code", "execution_count": 115, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "'\n" ] } ], "source": [ "print('\\'')" ] }, { "cell_type": "code", "execution_count": 116, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\u0007\n" ] } ], "source": [ "# 在python自带的IDE会响铃,在其他第三方IDE可能会不响\n", "# 即使在Python自带的IDE也可能会不响铃,响铃与否也跟电脑的设置有关\n", "# 这个\\a表示响铃,了解即可\n", "print('\\a')" ] }, { "cell_type": "code", "execution_count": 117, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hell World!\n" ] } ], "source": [ "# 退格就是键盘上的Backspace,在o后面有个退格,相当于敲了一下键盘上的Backspace键\n", "# 这下你能理解结果了吧\n", "print(\"Hello\\b World!\")" ] }, { "cell_type": "code", "execution_count": 118, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Worlddddd!\n" ] } ], "source": [ "# 回车,将\\r后面的内容移到字符串开头,\n", "# 并逐一替换开头部分的字符,直至将\\r后面的内容完全替换完成\n", "print(\"Hello\\rWorlddddd!\")" ] }, { "cell_type": "code", "execution_count": 119, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Wollo\n" ] } ], "source": [ "print(\"Hello\\rWo\")" ] }, { "cell_type": "code", "execution_count": 120, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello\n" ] } ], "source": [ "print(\"Hello\\r\")" ] }, { "cell_type": "code", "execution_count": 121, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello \f", " World!\n" ] } ], "source": [ "# 换页,将当前位置移到下页开头\n", "print(\"Hello \\f World!\")" ] }, { "cell_type": "code", "execution_count": 122, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\u0000\n" ] } ], "source": [ "# 空\n", "print(\"\\000\")" ] }, { "cell_type": "code", "execution_count": 123, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello\tWorld!\n" ] } ], "source": [ "# 横向制表符\n", "print(\"Hello\\tWorld!\")" ] }, { "cell_type": "code", "execution_count": 124, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello\n", "World!\n" ] } ], "source": [ "# 将当前位置移到下一行开头\n", "print(\"Hello\\nWorld!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "很抱歉,关于`\\other`,我没有找到合适的例子" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "在字符串前加上r可以消除字符中的转义,语法:`r\"带转义字符的字符串\"`" ] }, { "cell_type": "code", "execution_count": 125, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello\\nWorld!\n" ] } ], "source": [ "print(r\"Hello\\nWorld!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "思考题:分析《My Heart Will Go On》的歌词中出现频率最高的5个词语,系动词和标点不算。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 字符串格式化" ] }, { "cell_type": "markdown", "metadata": { "tags": [] }, "source": [ "**第一种方法:使用%**\n", "替代:用元组内的元素按照预设格式替代字符串中的内容。\n", "\n", "转换:`%s`称为转换说明符,标记了需要插入的转换值的位置。`s`表示会被格式化为字符串—如果不是字符串会自动转换为字符串。" ] }, { "cell_type": "code", "execution_count": 126, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "歌手邓紫棋,1991年出生于中国上海市,代表作有《光年之外》等。\n" ] } ], "source": [ "singer_template = \"歌手{name},{0}年出生于{nation},代表作有《{1}》等。\"\n", "print(singer_template.format(1991, '光年之外', nation = '中国上海市', name = '邓紫棋'))" ] }, { "cell_type": "code", "execution_count": 127, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'《最初的地方》由余光中作词,伍佰&杨乃文演唱'" ] }, "execution_count": 127, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"《最初的地方》由%s作词,%s&%s演唱\"%('余光中','伍佰','杨乃文')" ] }, { "cell_type": "code", "execution_count": 128, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'《最初的地方》有 2位演唱者'" ] }, "execution_count": 128, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# d表示十进制整数,3表示长度为3\n", "\"《最初的地方》有%3d位演唱者\"%(2.76076)" ] }, { "cell_type": "code", "execution_count": 129, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.08166666666666667" ] }, "execution_count": 129, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 把《我怀念的》的MV时长换算成小时\n", "(240 + 54)/3600.0" ] }, { "cell_type": "code", "execution_count": 130, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "'歌曲《我怀念的》的MV时长为0.081667小时'" ] }, "execution_count": 130, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 设置浮点数的格式时,默认在小数点后面显示6位小数\n", "\"歌曲《我怀念的》的MV时长为%f小时\"%(0.08166666)" ] }, { "cell_type": "code", "execution_count": 131, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'歌曲《我怀念的》的MV时长为0.08小时'" ] }, "execution_count": 131, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 长度为4,保留两位小数\n", "\"歌曲《我怀念的》的MV时长为%4.2f小时\"%(0.08166666)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "除`s`之外的其他类型说明符,参见教材表3-1。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**第二种方法:使用`format`函数与`{}`**\n", "\n", "1. `{}`字段可以通过默认顺序进行替换 :从左至由" ] }, { "cell_type": "code", "execution_count": 132, "metadata": {}, "outputs": [], "source": [ "singer_info = \"{}出生于{}年,身高{}m,代表作品有《{}》\"" ] }, { "cell_type": "code", "execution_count": 133, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'孙燕姿出生于1978年,身高1.62m,代表作品有《天黑黑》'" ] }, "execution_count": 133, "metadata": {}, "output_type": "execute_result" } ], "source": [ "singer_info.format('孙燕姿', 1978, 1.62, '天黑黑')" ] }, { "cell_type": "code", "execution_count": 134, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'伍佰出生于1968年,身高1.75m,代表作品有《挪威的森林》'" ] }, "execution_count": 134, "metadata": {}, "output_type": "execute_result" } ], "source": [ "singer_info.format('伍佰', 1968, 1.75, '挪威的森林')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "2. `{}`字段可以通过手工索引进行替换 :按照`{}`内的索引" ] }, { "cell_type": "code", "execution_count": 135, "metadata": {}, "outputs": [], "source": [ "singer_info = \"{3}出生于{0}年,身高{1}m,代表作品有《{2}》\"" ] }, { "cell_type": "code", "execution_count": 136, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'孙燕姿出生于1978年,身高1.62m,代表作品有《天黑黑》'" ] }, "execution_count": 136, "metadata": {}, "output_type": "execute_result" } ], "source": [ "singer_info.format(1978, 1.62, '天黑黑', '孙燕姿')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "3. `{}`字段可以按照字段名替换" ] }, { "cell_type": "code", "execution_count": 137, "metadata": {}, "outputs": [], "source": [ "singer_info = \"伍佰本名{true_name},配偶为{couple},现隶属唱片公司{company}\"" ] }, { "cell_type": "code", "execution_count": 138, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'伍佰本名陈文珮,配偶为吴俊霖,现隶属唱片公司环球音乐'" ] }, "execution_count": 138, "metadata": {}, "output_type": "execute_result" } ], "source": [ "singer_info.format(true_name = '陈文珮', couple = '吴俊霖', company = '环球音乐')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "4. {}字段名和{}字段索引可以混用, 位置参数在前,关键字参数在后" ] }, { "cell_type": "code", "execution_count": 139, "metadata": {}, "outputs": [], "source": [ "singer_info = \"{name}出生于{1}年,身高{0}m,代表作品有《{song}》\"" ] }, { "cell_type": "code", "execution_count": 140, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'孙燕姿出生于1978年,身高1.62m,代表作品有《天黑黑》'" ] }, "execution_count": 140, "metadata": {}, "output_type": "execute_result" } ], "source": [ "singer_info.format(1.62, 1978, song = '天黑黑', name = '孙燕姿')" ] }, { "cell_type": "code", "execution_count": 141, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1只青蛙1张嘴,2只眼睛4条腿,扑通~1声跳下水\n", "2只青蛙2张嘴,4只眼睛8条腿,扑通~扑通~2声跳下水\n", "3只青蛙3张嘴,6只眼睛12条腿,扑通~扑通~扑通~3声跳下水\n", "4只青蛙4张嘴,8只眼睛16条腿,扑通~扑通~扑通~扑通~4声跳下水\n", "5只青蛙5张嘴,10只眼睛20条腿,扑通~扑通~扑通~扑通~扑通~5声跳下水\n", "6只青蛙6张嘴,12只眼睛24条腿,扑通~扑通~扑通~扑通~扑通~扑通~6声跳下水\n", "7只青蛙7张嘴,14只眼睛28条腿,扑通~扑通~扑通~扑通~扑通~扑通~扑通~7声跳下水\n", "8只青蛙8张嘴,16只眼睛32条腿,扑通~扑通~扑通~扑通~扑通~扑通~扑通~扑通~8声跳下水\n", "9只青蛙9张嘴,18只眼睛36条腿,扑通~扑通~扑通~扑通~扑通~扑通~扑通~扑通~扑通~9声跳下水\n" ] } ], "source": [ "for num in range(1,10):\n", " str3 = '{}只青蛙{}张嘴,{}只眼睛{}条腿,'.format(num, num, 2*num, 4*num) + '扑通~'*num + '{}声跳下水'.format(num)\n", " print(str3) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## `format`方法详解" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " `{:}`内可填写字符串转换的格式,冒号前可写**字段名**或者**索引**,冒号后填写待格式化字符串的**格式**\n", "\n", "- `^`, `<`, `>` 分别是居中、左对齐、右对齐,后面带宽度;\n", "- `:`号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。\n", "- `+`表示在正数前显示 +,负数前显示 -;` `(空格)表示在正数前加空格\n", "- `b`、`d`、`o`、`x` 分别是二进制、十进制、八进制、十六进制。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```\n", "format_spec ::= [[fill]align][sign][#][0][width][grouping_option][.precision][type]\n", "fill ::= \n", "align ::= \"<\" | \">\" | \"=\" | \"^\"\n", "sign ::= \"+\" | \"-\" | \" \"\n", "width ::= digit+\n", "grouping_option ::= \"_\" | \",\"\n", "precision ::= digit+\n", "type ::= \"b\" | \"c\" | \"d\" | \"e\" | \"E\" | \"f\" | \"F\" | \"g\" | \"G\" | \"n\" | \"o\" | \"s\" | \"x\" | \"X\" | \"%\"\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `[fill]align`参数" ] }, { "cell_type": "code", "execution_count": 142, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'?5?'" ] }, "execution_count": 142, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 使用?作为填充字符,指定对齐方式为居中,指定宽度为3\n", "'{:?^3}'.format(5)" ] }, { "cell_type": "code", "execution_count": 143, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'-?5'" ] }, "execution_count": 143, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 使用?作为填充字符,数字默认右对齐,强制在正负号与数字之间进行填充\n", "'{:?=3}'.format(-5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `sign`参数" ] }, { "cell_type": "code", "execution_count": 144, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'+5'" ] }, "execution_count": 144, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 对数字使用正负号\n", "'{:+}'.format(5)" ] }, { "cell_type": "code", "execution_count": 145, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' 5'" ] }, "execution_count": 145, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 对正数使用一个空格作为前导\n", "'{: }'.format(5)" ] }, { "cell_type": "code", "execution_count": 146, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'-5'" ] }, "execution_count": 146, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 对负数使用符号作为前导\n", "'{: }'.format(-5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `width`参数" ] }, { "cell_type": "code", "execution_count": 147, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Tom '" ] }, "execution_count": 147, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 指定宽度为5,字符串默认左对齐,默认填充空格\n", "'{:5}'.format('Tom')" ] }, { "cell_type": "code", "execution_count": 148, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'00023'" ] }, "execution_count": 148, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 指定宽度为5,数字默认右边对齐,对数字启用0填充\n", "'{:05}'.format(23)" ] }, { "cell_type": "code", "execution_count": 149, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' 23'" ] }, "execution_count": 149, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 指定宽度为5,数字默认右边对齐,默认使用空格填充\n", "'{:5}'.format(23)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `grouping_option`参数" ] }, { "cell_type": "code", "execution_count": 150, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'1,773.8799'" ] }, "execution_count": 150, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 使用逗号作为整数部分的千分位分隔符\n", "'{:,}'.format(1773.8799)" ] }, { "cell_type": "code", "execution_count": 151, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'1_773.8799'" ] }, "execution_count": 151, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 使用下划线作为整数部分的千分位分隔符\n", "'{:_}'.format(1773.8799)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `.precision`参数" ] }, { "cell_type": "code", "execution_count": 152, "metadata": {}, "outputs": [], "source": [ "import math" ] }, { "cell_type": "code", "execution_count": 153, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'3.142'" ] }, "execution_count": 153, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 对浮点数,保留三位小数,常用\n", "'{:.3f}'.format(math.pi)" ] }, { "cell_type": "code", "execution_count": 154, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'pyt'" ] }, "execution_count": 154, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 对字符串,显示三个字符,不常用\n", "'{:.3}'.format('python')" ] }, { "cell_type": "code", "execution_count": 155, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'3.142'" ] }, "execution_count": 155, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 不指定f,对浮点数,显示3位数字,四舍五入,不常用\n", "'{:.4}'.format(3.1415926)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `type`参数 - 整数" ] }, { "cell_type": "code", "execution_count": 156, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'1011'" ] }, "execution_count": 156, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 显示填充数字的二进制形式\n", "'{:b}'.format(11)" ] }, { "cell_type": "code", "execution_count": 157, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'13'" ] }, "execution_count": 157, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 显示填充数字的八进制形式\n", "'{:o}'.format(11)" ] }, { "cell_type": "code", "execution_count": 158, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'b'" ] }, "execution_count": 158, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 显示填充数字的十六进制形式\n", "'{:x}'.format(11)" ] }, { "cell_type": "code", "execution_count": 159, "metadata": {}, "outputs": [], "source": [ "# c表示,你这里填充的是一个整数,并且这个整数对应字符的unicode编码值\n", "str_3 = \"{:c}\"" ] }, { "cell_type": "code", "execution_count": 160, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'N'" ] }, "execution_count": 160, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 对字符串进行格式化输出\n", "str_3.format(78)" ] }, { "cell_type": "code", "execution_count": 161, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "78" ] }, "execution_count": 161, "metadata": {}, "output_type": "execute_result" } ], "source": [ "ord('N')" ] }, { "cell_type": "code", "execution_count": 162, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'N'" ] }, "execution_count": 162, "metadata": {}, "output_type": "execute_result" } ], "source": [ "chr(78)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `type`参数 - 浮点数" ] }, { "cell_type": "code", "execution_count": 163, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'3.128e+16'" ] }, "execution_count": 163, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 保留三位小数,采用科学计数法表示数字\n", "'{:.3e}'.format(31284957634983947)" ] }, { "cell_type": "code", "execution_count": 164, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'3.1285E+25'" ] }, "execution_count": 164, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 自动选择使用科学计数法还是普通浮点数表示数字\n", "'{:G}'.format(31284957634983947980568995)" ] }, { "cell_type": "code", "execution_count": 165, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'313000'" ] }, "execution_count": 165, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 自动选择使用科学计数法还是普通浮点数表示数字\n", "'{:G}'.format(312999.8397526735194523993)" ] }, { "cell_type": "code", "execution_count": 166, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'31.3'" ] }, "execution_count": 166, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 自动选择使用科学计数法还是普通浮点数表示数字\n", "'{:G}'.format(31.29998397526735194523993)" ] }, { "cell_type": "code", "execution_count": 167, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'3.13E+22'" ] }, "execution_count": 167, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 自动选择使用科学计数法还是普通浮点数表示数字\n", "'{:G}'.format(31299983975267351945239.93)" ] }, { "cell_type": "code", "execution_count": 168, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'27.8647%'" ] }, "execution_count": 168, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 把数字变为百分数,保留4位小数\n", "'{:.4%}'.format(0.278647)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 综合示例" ] }, { "cell_type": "code", "execution_count": 169, "metadata": {}, "outputs": [], "source": [ "# /表示填充字符,如果不指定默认就是空格填充;\n", "# ^表示居中显示\n", "# +表示在正数前面加正号,负数前面加负号\n", "# 10表示宽度为10\n", "# .2f表示保留两位小数" ] }, { "cell_type": "code", "execution_count": 170, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'//+3.14///'" ] }, "execution_count": 170, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str4 = \"{:/^+10.2f}\"\n", "str4.format(3.1415926) # //+3.14///" ] }, { "cell_type": "code", "execution_count": 171, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 张三 的成绩是+91.50 ,班级排名第5\n", "+4.560000e+02的二进制形式为+0b111001000,八进制为+0o710,十六进制为+0X1C8\n", "zjz 的年收入为60023元,月平均5001.92元\n", "zjz 的年收入为60023元,月平均5001.92元\n", "Tom 的年收入为 67元,月平均 5.58元\n" ] } ], "source": [ "str5 = \"{:^10.5s}的成绩是{:<+10.2f},班级排名第{:d}\"\n", "print(str5.format(\"张三\", 91.5, 5))\n", "str6 = \"{num:+e}的二进制形式为{num:+#b},八进制为{num:+#o},十六进制为{num:+#X}\"\n", "print(str6.format(num=456))\n", "str7 = \"{:5.3s}的年收入为{:5d}元,月平均{:5.2f}元\"\n", "print(str7.format('zjzhang', 60023, 60023/12.0))\n", "str8 = \"{:5.3s}的年收入为{:4d}元,月平均{:5.2f}元\"\n", "print(str8.format('zjzhang', 60023, 60023/12.0))\n", "print(str8.format('Tomy', 67, 67/12.0))" ] }, { "cell_type": "code", "execution_count": 172, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'002'" ] }, "execution_count": 172, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 右对齐,填充字符为0,宽度指定为3\n", "'{:0>3}'.format(2)" ] }, { "cell_type": "code", "execution_count": 173, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'002'" ] }, "execution_count": 173, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 宽度为3,对数字启用0填充\n", "'{:03}'.format(2)" ] }, { "cell_type": "code", "execution_count": 174, "metadata": {}, "outputs": [], "source": [ "str_1 = \"{:/^+10.2f}\"" ] }, { "cell_type": "code", "execution_count": 175, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "'//+3.14///'" ] }, "execution_count": 175, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str_1.format(3.1415926)" ] }, { "cell_type": "code", "execution_count": 176, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'//-3.14///'" ] }, "execution_count": 176, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str_1.format(-3.1415926)" ] }, { "cell_type": "code", "execution_count": 177, "metadata": { "scrolled": true }, "outputs": [], "source": [ "# 把刚才的加号换成空格,表示在正数前面加空格\n", "str_2 = \"{:/^ 10.2f}\"" ] }, { "cell_type": "code", "execution_count": 178, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'// 3.14///'" ] }, "execution_count": 178, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str_2.format(3.1415926)" ] }, { "cell_type": "code", "execution_count": 179, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "'//-3.14///'" ] }, "execution_count": 179, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str_2.format(-3.1415926)" ] }, { "cell_type": "code", "execution_count": 180, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'0b1011'" ] }, "execution_count": 180, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 显示填充数字的二进制形式,加前缀\n", "'{:#b}'.format(11)" ] }, { "cell_type": "code", "execution_count": 181, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'13'" ] }, "execution_count": 181, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'{:x}'.format(19)" ] }, { "cell_type": "code", "execution_count": 182, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'0x13'" ] }, "execution_count": 182, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'{:#x}'.format(19)" ] }, { "cell_type": "code", "execution_count": 183, "metadata": {}, "outputs": [], "source": [ "str_3 = \"{:/^4.2}\"" ] }, { "cell_type": "code", "execution_count": 184, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'/阿里/'" ] }, "execution_count": 184, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 对字符串进行格式化输出\n", "str_3.format('阿里巴巴商学院')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**其他几个需要注意的点**\n", "\n", "- 字符串的精度是对字符串的直接切片\n", "- 浮点数精度存在四舍五入,首先保证小数部分,当长度超过宽度时,最初设置的宽度将不起作用;\n", "- 整数不允许使用精度\n", "- 默认对齐方式是:字符串左对齐,数值右对齐" ] }, { "cell_type": "code", "execution_count": 185, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'jupy'" ] }, "execution_count": 185, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 字符串的精度是对字符串的直接切片\n", "'{:.4}'.format('jupyter')" ] }, { "cell_type": "code", "execution_count": 186, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'3.142'" ] }, "execution_count": 186, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 浮点数精度存在四舍五入\n", "'{:.3f}'.format(3.1415926)" ] }, { "cell_type": "code", "execution_count": 187, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'3.1416'" ] }, "execution_count": 187, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 首先保证小数部分,所以先保留4位小数\n", "# 但是我设置的宽度为5,此时,保留完4位小数之后的数字长度超过5,所以,这里设置的宽度5将失效\n", "'{:5.4f}'.format(3.1415926)" ] }, { "cell_type": "code", "execution_count": 188, "metadata": {}, "outputs": [], "source": [ "# 整数不允许使用精度,下面代码会报错\n", "# '{:.4}'.format(31415926)" ] }, { "cell_type": "code", "execution_count": 189, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'py '" ] }, "execution_count": 189, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 字符串默认左对齐,指定了宽度为6,用切片操作只取2个字符\n", "'{:6.2s}'.format('pycharm')" ] }, { "cell_type": "code", "execution_count": 190, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' 3.14'" ] }, "execution_count": 190, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 数值默认右对齐,指定了宽度为10,.2f表示保留两位小数\n", "'{:10.2f}'.format(3.1415926)" ] }, { "cell_type": "code", "execution_count": 191, "metadata": {}, "outputs": [ { "name": "stdin", "output_type": "stream", "text": [ "Please enter width: 50\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "==================================================\n", "Item Price\n", "--------------------------------------------------\n", "Apples 0.40\n", "Pears 0.50\n", "Cantaloupes 1.92\n", "Dried Apricots (16 oz.) 8.00\n", "Prunes (4 lbs.) 12.00\n", "==================================================\n" ] } ], "source": [ "# 打印价格表的例子\n", "\n", "width = int(input('Please enter width: '))\n", "\n", "price_width = 10\n", "item_width = width - price_width\n", "\n", "header_fmt = '{{:{}}}{{:>{}}}'.format(item_width, price_width)\n", "fmt = '{{:{}}}{{:>{}.2f}}'.format(item_width, price_width)\n", "\n", "print('=' * width)\n", "\n", "print(header_fmt.format('Item', 'Price'))\n", "\n", "print('-' * width)\n", "\n", "print(fmt.format('Apples', 0.4))\n", "print(fmt.format('Pears', 0.5))\n", "print(fmt.format('Cantaloupes', 1.92))\n", "print(fmt.format('Dried Apricots (16 oz.)', 8))\n", "print(fmt.format('Prunes (4 lbs.)', 12))\n", "\n", "print('=' * width) # 50" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "理解上面例子的关键是要能准确理解两个字符串格式化表达式:\n", "\n", "1. `header_fmt = '{{:{}}}{{:>{}}}'.format(item_width, price_width)`\n", "\n", "2. `header_fmt = '{{:{}}}{{:>{}}}'.format(item_width, price_width)`" ] }, { "cell_type": "code", "execution_count": 192, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(40, 10)" ] }, "execution_count": 192, "metadata": {}, "output_type": "execute_result" } ], "source": [ "item_width, price_width" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "花括号`{`和`}`是用来表示字符串格式化表达式的,那么我要想在字符串格式化表达式中让`{`和`}`作为普通字符出现,怎么办呢?" ] }, { "cell_type": "code", "execution_count": 193, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'{}你看,我左边是什么'" ] }, "execution_count": 193, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'{{}}{text}'.format(text = '你看,我左边是什么')" ] }, { "cell_type": "code", "execution_count": 194, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'{你看,我左边是什么'" ] }, "execution_count": 194, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'{{{text}'.format(text = '你看,我左边是什么')" ] }, { "cell_type": "code", "execution_count": 195, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'你看,我右边是什么}'" ] }, "execution_count": 195, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'{text}}}'.format(text = '你看,我右边是什么')" ] }, { "cell_type": "code", "execution_count": 196, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'%是百分号'" ] }, "execution_count": 196, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'%%%s'%('是百分号')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "在字符串格式化表达式中`{{`表示普通字符`{`,`}}`表示普通字符`}`,`%%`表示普通字符`%`。" ] }, { "cell_type": "code", "execution_count": 197, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'{:40}{:>10}'" ] }, "execution_count": 197, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 下面语句的执行结果是一个新的字符串格式化表达式\n", "'{{:{}}}{{:>{}}}'.format(item_width, price_width)" ] }, { "cell_type": "code", "execution_count": 198, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'{:40}{:>10.2f}'" ] }, "execution_count": 198, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 下面语句的执行结果是一个新的字符串格式化表达式\n", "'{{:{}}}{{:>{}.2f}}'.format(item_width, price_width)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "现在在理解上面打印小票的代码就很容易了吧 ^_^" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "f-string用法示例如下:" ] }, { "cell_type": "code", "execution_count": 199, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'有一个圆,半径为3.00,面积为28.27'" ] }, "execution_count": 199, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import math\n", "radius = 3\n", "f\"有一个圆,半径为{radius:.2f},面积为{math.pi*(radius**2):.2f}\"" ] }, { "cell_type": "code", "execution_count": 200, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'角度值为80.00,弧度值为1.39626,其正弦值为0.98'" ] }, "execution_count": 200, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = 80\n", "F\"角度值为{x:.2f},弧度值为{math.radians(x):.5f},其正弦值为{math.sin(math.radians(x)):.2f}\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "总结回顾一下:\n", "\n", "1. 字符串(string)、列表(list)、元组(tuple)都是序列(sequence)类型,可以通过下标访问,可以通过`for...in`循环访问\n", " - 字符串放在两个引号(单引号、双引号、三引号)之间;\n", " - 列表放在两个中括号之间;\n", " - 元组放在两个圆括号之间;\n", " \n", " \n", "2. 集合无序,不可以通过下标访问,可以通过`for...in`循环访问\n", "\n", "\n", "3. 上述四者在一定条件下可以相互转换" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "思考题:令变量`lyrics`表示歌曲《My Heart Will Go On》的歌词字符串,如下,请分别将其转换为**列表**,**元组**,**集合**,并赋值给变量`lyrics_list`,`lyrics_tuple`,`lyrics_set`,要求列表,元组,集合中的元素只包含合法单词,且单词均为小写。" ] }, { "cell_type": "code", "execution_count": 201, "metadata": {}, "outputs": [], "source": [ "lyrics = '''Every night in my dreams\n", "I see you, I feel you,\n", "That is how I know you go on\n", "\n", "Far across the distance\n", "And spaces between us\n", "You have come to show you go on\n", "\n", "Near, far, wherever you are\n", "I believe that the heart does go on\n", "Once more you open the door\n", "And you are here in my heart\n", "And my heart will go on and on\n", "\n", "Love can touch us one time\n", "And last for a lifetime\n", "And never let go till we are gone\n", "\n", "Love was when I loved you\n", "One true time I hold to\n", "In my life we will always go on\n", "\n", "Near, far, wherever you are\n", "I believe that the heart does go on\n", "Once more you open the door\n", "And you are here in my heart\n", "And my heart will go on and on\n", "\n", "You are here, there is nothing I fear,\n", "And I know that my heart will go on\n", "We will stay forever this way\n", "You are safe in my heart\n", "And my heart will go on and on'''" ] }, { "cell_type": "code", "execution_count": 202, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "END\n" ] } ], "source": [ "print('END')" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.7" } }, "nbformat": 4, "nbformat_minor": 4 }