Duk*_*gal 50 python string go python-3.x
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可以做某事吗?
Mar*_*eed 87
它有一个功能而不是操作员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)
}
Run Code Online (Sandbox Code Playgroud)
请注意,我用过utf8.RuneCountInString(x)而不是len(x); 前者计算"符文"(Unicode代码点),而后者计算字节数.在这种情况下"my new text is this long",差异并不重要,因为所有字符只有一个字节,但养成指定你的意思的习惯是好的:
len("?") //=> 2
utf8.RuneCountInString("?") //=> 1
Run Code Online (Sandbox Code Playgroud)
(在Python 2中,len计算普通字符串上的字节和Unicode字符串上的符文(u'...'):
>>> len('?') #=> 2
>>> len(u'?') #=> 1
Run Code Online (Sandbox Code Playgroud)
在Python 3中,普通字符串是 Unicode字符串并len计算符文; 如果要计算字节数,则必须将字符串编码为bytearray第一个:
>>> len('?') #=> 1
>>> len('?'.encode('utf-8')) #=> 2
Run Code Online (Sandbox Code Playgroud)
在Go中,只有一种字符串.所以你不必转换,但你必须选择与你想要的语义相匹配的函数.)
icz*_*cza 14
是的,它可以,虽然不是运营商,但在标准库中具有功能.
使用简单的循环将非常容易,但标准库为您提供了高度优化的版本:strings.Repeat().
你的例子:
x := "my new text is this long"
y := strings.Repeat("#", len(x))
fmt.Println(y)
Run Code Online (Sandbox Code Playgroud)
在Go Playground尝试一下.
注意:len(x)是字符串的"字节"长度(字节数)(以UTF-8编码,这就是Go在内存中存储字符串的方式).如果你想要字符数(符文),请使用utf8.RuneCountInString().
| 归档时间: |
|
| 查看次数: |
17364 次 |
| 最近记录: |