首页 > 解决方案 > shell command # can't be carry out when it not used for comments on colab

问题描述

I'm confused about this code! Why # cant't play a role that takes the length of a string?

 string="abcd"

 !echo ${#string}

In fact, the code behind # has become commented and cannot be executed!

Any advice?

标签: jupyter-notebookgoogle-colaboratorymagic-string

解决方案


这可以正常工作,但是您不能以这种方式混合 python 和 bash 变量。试试这个:

!string="abcd" && echo ${#string}

这两个语句必须在同一行,因为在 IPython 中,每个!语句都会打开一个临时子 shell,并且变量不会在 shell 之间持久化。如果你想使用多行 bash 程序,你可以使用%%bashcell magic 来代替:

%%bash
string="abcd"
echo  ${#string}

推荐阅读