小编典典

Golang 可以像 Python 那样乘以字符串吗?

go

Python 可以像这样将字符串相乘:

Python 3.4.3 (default, Mar 26 2015, 22:03:40)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 'my new text is this long'
>>> y = '#' * len(x)
>>> y
'########################'
>>>

Golang 能以某种方式做同样的事情吗?


阅读 238

收藏
2021-12-16

共1个答案

小编典典

它有一个函数而不是一个运算符,strings.Repeat。这是您的 Python 示例的一个端口,您可以在此处运行:

package main

import (
    "fmt"
    "strings"
    "unicode/utf8"
)

func main() {
    x := "my new text is this long"
    y := strings.Repeat("#", utf8.RuneCountInString(x))
    fmt.Println(x)
    fmt.Println(y)
}

请注意,我使用了utf8.RuneCountInString(x)而不是len(x); 前者计算“符文”(Unicode 代码点),而后者计算字节。在 的情况下"my new text is this long",差异无关紧要,因为所有字符都只有一个字节,但是养成指定您的意思的习惯是很好的:

len("ā") //=> 2
utf8.RuneCountInString("ā") //=> 1

由于这是一个 Python 比较问题,请注意在 Python 中, one 函数len根据您调用它的内容计算不同的内容。在 Python 2 中,它计算纯字符串上的字节数和 Unicode 字符串上的符文 ( u'...'):

Python 2.7.18 (default, Aug 15 2020, 17:03:20)
>>> len('ā') #=> 2
>>> len(u'ā') #=> 1

而在现代 Python 中,纯字符串Unicode 字符串:

Python 3.9.6 (default, Jun 29 2021, 19:36:19) 
>>> len('ā') #=> 1

如果要计算字节数,则需要bytearray先将字符串编码为一个:

>>> len('ā'.encode('UTF-8')) #=> 2

所以Python有多种类型的字符串和一个函数来获取它们的长度;Go 只有一种字符串,但你必须选择与你想要的语义匹配的长度函数。

2021-12-16