From f39cc5dccba78f2445f0c72006e2dd333a713008 Mon Sep 17 00:00:00 2001 From: Hui Lan Date: Mon, 29 Jul 2019 18:40:51 +0800 Subject: =?UTF-8?q?LectureNotesOnPython.rst:=20=E5=8A=A0=E5=85=A5=E4=B8=80?= =?UTF-8?q?=E4=B8=AA=E6=96=B0=E9=97=AE=E9=A2=98=20'apple=20banana=20applep?= =?UTF-8?q?ie'=20=E4=B8=AD=E6=95=B0=E5=87=BA=20'apple'=20=E7=9A=84?= =?UTF-8?q?=E4=B8=AA=E6=95=B0=EF=BC=8C=20=E4=B8=8D=E8=A6=81=E5=8C=85?= =?UTF-8?q?=E6=8B=AC=20'applepie'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- LectureNotesOnPython.rst | 54 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 52 insertions(+), 2 deletions(-) (limited to 'LectureNotesOnPython.rst') diff --git a/LectureNotesOnPython.rst b/LectureNotesOnPython.rst index 61dd22a..ce9fdf9 100644 --- a/LectureNotesOnPython.rst +++ b/LectureNotesOnPython.rst @@ -410,9 +410,21 @@ a是变量名。 'a'是值。 a = 'a' 这个语句要从右边向左边读, fruit = 'apple banana apple' print(fruit.count('apple')) - +问题: 数出字符串'apple banana applepie'中, apple出现的次数? 希望的答案是1。 + +.. code:: python + + fruit = 'apple banana applepie' + # Solution 1 + from collections import Counter + Counter(fruit.split())['apple'] + # Solution 2, use count = 0 and for loop + + # Solution 3 + sum([x == 'apple' for x in fruit.split()]) + 问题: 如何获得第一个p出现的位置? @@ -437,6 +449,42 @@ a是变量名。 'a'是值。 a = 'a' 这个语句要从右边向左边读, - t=my*999 # 等号前后没有空格 (编程风格差), 应该是 t = 'my' * 999 +**练习** 写一个脚本, 统计输入字符串中,英文字母的个数(忽略空白字符如空格)。 如果还要忽略标点符号呢? + + +.. code:: python + + s = 'i am a boy' + print(len(s)) + + # Method 1 + n = len(s) - s.count(' ') + print(n) + + # Method 2 + t = s.replace(' ', '') + print(len(t)) + + # Method 3 + lst = s.split() + t = ''.join(lst) + print(len(t)) + + # Method 4 + t = '' + for x in s: + if x != ' ': + t += x + print(len(t)) + + # Method 5 + import string + t = '' + for x in s: + if x in string.ascii_letters: + t += x + print(len(t)) + **练习** 把下面这段文字转成字符串并存在变量boris中。 @@ -486,7 +534,9 @@ fruit中有多少apple? 有多少banana? 有多少orange? 数的时候你 Python脚本文件命令行执行 -------------------------------------- -python a.py。 +如果你的所有的语句都存在脚本 a.py 中, 那么在脚本所在的那个路径下, 在命令行输入以下命令就能执行该脚本。 + +| python a.py。 -- cgit v1.2.1