Python 挑战:字符串操作

介绍

我们之前通过4个课程学习了一些基本的 Python 3 知识。现在我们就来用一个挑战实验来巩固一下我们的实验效果。

目标

在/home/shiyanlou/Code创建一个 名为 FindDigits.py 的Python 脚本,请读取一串字符串并且把其中所有的数字组成一个新的字符串,并且打印出来。我们提供的字符串可以通过在命令行中输入如下代码来获取。

1
wget http://labfile.oss.aliyuncs.com/courses/790/String.txt

P.S 如果大家想要通过 open() 函数来获取 String.txt 中的字符串,请在 open() 函数中写下 String.txt 的绝对路径,如 file = open(‘/home/shiyanlou/Code/String.txt’),否则系统测试会通不过 :(

提示语

使用循环来访问字符串中的单个字符

1
isdigit()

记得把新的字符串打印出来,print()函数记得要加括号(这里是Python3 的主场!敲黑板)

知识点

  • 循环
  • 字符串操作

来源

实验楼团队

答案

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/env python3

with open('/home/shiyanlou/Code/String.txt') as f:
s = f.read()

numstr = []
for c in s:
if c.isdigit():
numstr.append(c)

new_str = ''.join(numstr)
print(new_str)

使用列表推导式

1
2
3
4
5
#!/usr/bin/env python3

with open('/home/shiyanlou/Code/String.txt') as f:
s = f.read()
print(''.join([c for c in s if c.isdigit()]))