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
'########################'
>>>
Run Code Online (Sandbox Code Playgroud)
Golang可以做某事吗?
我正在尝试优化 Go 中的 stringpad 库。到目前为止,我发现用已知字符值(例如 0 或“”)填充字符串(实际上是 bytes.Buffer)的唯一方法是使用 for 循环。
代码片段是:
// PadLeft pads string on left side with p, c times
func PadLeft(s string, p string, c int) string {
var t bytes.Buffer
if c <= 0 {
return s
}
if len(p) < 1 {
return s
}
for i := 0; i < c; i++ {
t.WriteString(p)
}
t.WriteString(s)
return t.String()
}
Run Code Online (Sandbox Code Playgroud)
字符串填充越大,我相信 t 缓冲区的内存副本就越多。是否有一种更优雅的方法来在初始化时使用已知值创建已知大小的缓冲区?