python输入方式为替换输入_使用jupyter在python3中用字符串替换标准输入

I am trying to replace the standard input by a previously defined string.

After browsing on stack overflow, I found several solutions (though mostly for python2).

The solution below for example was tested in ideone.com and seems to work, however when I tried to add it to my code in my jupyter notebook the redefinition of the standard input gets ignored.

Is this due to jupyter or some problem in my code, and how could I fix it ?

import io,sys

s = io.StringIO('Hello, world!')

sys.stdin = s

sys.__stdin__ = s

r = input()

print(r)

解决方案

The short answer is that Jupyter notebook doesn't support stdin/stdout, so you can't rely on them in notebook code.

The longer answer is that stdin/stdout are implemented differently in Jupyter than in standard Python, owing to the particulars of how Jupyter accepts input/displays output. If you want something that will ask for user input if there's no input currently available, this would work:

import io,sys

# if sys.stdin is empty, the user will be prompted for input

# sys.stdin = io.StringIO('')

sys.stdin = io.StringIO('Hello world')

r = sys.stdin.readline()

if not r:

r = builtins.input()

print(r)

Reference

stdin/stdout is spoken of somewhat eliptically in the Jupyter/IPython docs. Here's a relevant direct quote, though, from the %reset magic docs:

Calling this magic from clients that do not implement standard input, such as the ipython notebook interface, will reset the namespace without confirmation.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 Python 的 `openpyxl` 库来读取和写入 Excel 文件,并使用字符串的 `replace()` 方法来替换单元格中的内容。下面是一个示例代码,演示了如何实现你的需求: ```python from openpyxl import load_workbook def replace_in_excel(filename, sheetname, search_str, replace_str): # 加载 Excel 文件 wb = load_workbook(filename) sheet = wb[sheetname] # 遍历单元格,替换内容 for row in sheet.iter_rows(values_only=True): for cell in row: if isinstance(cell, str): original_value = cell new_value = original_value.replace(search_str, replace_str) cell.value = f"{original_value} -> {new_value}" # 保存修改后的 Excel 文件 wb.save(f"modified_{filename}") # 示例用法 replace_in_excel("example.xlsx", "Sheet1", "old", "new") ``` 这个示例中,我们首先加载 Excel 文件,然后遍历每个单元格,如果单元格的值是字符串类型,则使用 `replace()` 方法替换指定的字符。替换后,在单元格中使用 `->` 符号将原文和替换后的内容连接起来。最后,保存修改后的 Excel 文件。 请确保你已经安装了 `openpyxl` 库,可以使用 `pip install openpyxl` 命令进行安装。同时,将代码中的 `example.xlsx` 替换为你实际的 Excel 文件路径,`Sheet1` 替换为你想要操作的工作表名称,`old` 替换为你要查找的字符,`new` 替换为你要替换的字符。 希望这个示例能帮助到你!如果有任何问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值