写了一个格式化字符串的包。提供类似于Python的写法,目前只能做玩具
package helper
import (
"fmt"
"strconv"
"strings"
)
func Fmt(format string, args ...interface{}) string {
argsWithKey := []string{}
for i, v := range args {
argsWithKey = append(argsWithKey, "{"+strconv.Itoa(i)+"}")
argsWithKey = append(argsWithKey, fmt.Sprintf("%v", v))
}
format = getFormat(format)
r := strings.NewReplacer(argsWithKey...)
return r.Replace(format)
}
func getFormat(format string) string {
// 先用 {{ }}切分成数组
arr := []string{}
start := 0
i := 0
for i < len(format) {
// 找到一个 {{
if format[i] == '{' && i+1 < len(format) && format[i+1] == '{' {
arr = append(arr, format[start:i])
arr = append(arr, "{{")
i += 2
start = i
}
// 找到一个 }}
if format[i] == '}' && i+1 < len(format) && format[i+1] == '}' {
arr = append(arr, format[start:i])
arr = append(arr, "}}")
i += 2
start = i
}
i++
}
if start < len(format) {
arr = append(arr, format[start:])
}
// 此时,只剩下了 {},往里面填数字,{} {} -> {0} {1}
quotoNum := 0
for arrIndex, v := range arr {
tempStr := v
for true {
pos := strings.Index(tempStr, "{}")
if pos == -1 {
break
}
tempStr = tempStr[:pos] + "{" + strconv.Itoa(quotoNum) + "}" +
tempStr[pos+2:]
quotoNum++
}
arr[arrIndex] = tempStr
}
result := ""
for _, v := range arr {
v = strings.Replace(v, "{{", "{", -1)
v = strings.Replace(v, "}}", "}", -1)
result += v
}
return result
}
测试:
logger.Infoln(helper.Fmt("{0}ha{1}{{{1}", "hello", "world"))
logger.Infoln(helper.Fmt("{}ha{}{{{}", "hello", "world", "haha"))
logger.Infoln(helper.Fmt("{{}}{}", "hello"))
logger.Infoln(helper.Fmt("{{}}{}{}", "hello", "world"))
logger.Infoln(helper.Fmt("{} is a big.{}", "大猪", "ha"))