diff options
author | Hui Lan <lanhui@zjnu.edu.cn> | 2019-07-29 18:40:51 +0800 |
---|---|---|
committer | Hui Lan <lanhui@zjnu.edu.cn> | 2019-07-29 18:40:51 +0800 |
commit | f39cc5dccba78f2445f0c72006e2dd333a713008 (patch) | |
tree | f50c45f0b78d41edbb0357dc8712eed04e8a07da /LectureNotesOnPython.rst | |
parent | 6a1bb3037d35b9d14fa21d9f27f8d444188b208d (diff) |
LectureNotesOnPython.rst: 加入一个新问题 'apple banana applepie' 中数出 'apple' 的个数, 不要包括 'applepie'
Diffstat (limited to 'LectureNotesOnPython.rst')
-rw-r--r-- | LectureNotesOnPython.rst | 54 |
1 files changed, 52 insertions, 2 deletions
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。 |