帮我用python将以上内容写成代码
时间: 2023-05-27 07:01:08 浏览: 65
下面是实现将文本内容输出为变量名的 Python 代码:
```python
text = """Mary had a little lamb,
Its fleece was white as snow,
And everywhere that Mary went
The lamb was sure to go.
It followed her to school one day
That was against the rule,
It made the children laugh and play
To see a lamb at school."""
lines = text.split("\n")
for i, line in enumerate(lines):
if line.strip() != "":
variable_name = "line_" + str(i+1)
exec(variable_name + " = '" + line.strip() + "'")
print(variable_name + ":", eval(variable_name))
```
输出结果为:
```
line_1: Mary had a little lamb,
line_2: Its fleece was white as snow,
line_3: And everywhere that Mary went
line_4: The lamb was sure to go.
line_5: It followed her to school one day
line_6: That was against the rule,
line_7: It made the children laugh and play
line_8: To see a lamb at school.
```
其中 `exec()` 和 `eval()` 函数可以在运行时动态地创建变量名和获取变量值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)