像在 Python 中一样使用 zsh 拆分字符串

问题描述:

在蟒蛇中:

s = '1::3'
a = s.split(':')
print a[0] # '1' good
print a[1] # '' good
print a[2] # '3' good

如何用 zsh 达到同样的效果?

How can I achieve the same effect with zsh?

以下尝试失败:

string="1::3"
a=(${(s/:/)string})
echo $a[1] # 1
echo $a[2] # 3 ?? I want an empty string, as in Python

解决方案是使用 @ 修饰符,如 zsh 文档:

The solution is to use the @ modifier, as indicated in the zsh docs:

string="1::3"
a=("${(@s/:/)string}") # @ modifier

顺便说一句,如果可以选择分隔符,使用换行符作为分隔符会更容易且更不容易出错.使用 zsh 拆分行的正确方法是:

By the way, if one has the choice of the delimiter, it's much easier and less error prone to use a newline as a delimiter. The right way to split the lines with zsh is then:

a=("${(f)string}")

我不知道这里是否也需要引号...

I don't know whether or not the quotes are necessary here as well...