fmt.Println打印出格式化占位符,例如%s。

huangapple go评论98阅读模式
英文:

fmt.Println prints out format verbs like %s

问题

我已经编写了一段代码,旨在打印出一个映射中的键和值。

kvs := map[string]string{"a": "apple", "b": "banana"}
for k, v := range kvs {
    fmt.Println("%s -> %s\n", k, v)
}

我期望的输出是:

a -> apple
b -> banana

但实际输出是:

%s -> %s
a apple
%s -> %s
b banana
英文:

I've written code that is intended to print out keys and values in a map.

kvs := map[string]string{"a": "apple", "b": "banana"}
for k, v := range kvs {
    fmt.Println("%s -> %s\n", k, v)
}

I'm expecting the output to be:

a -> apple
b -> banana

But the output is actually:

%s -> %s
a apple
%s -> %s
b banana

答案1

得分: 12

看起来你正在尝试使用字符串格式化,而fmt.Println不支持这个功能。

根据godocs的说明:

> Printf 根据格式说明符进行格式化

> Println 使用默认格式进行格式化

以下代码将给出你想要的输出结果:

package main

import "fmt"

func main() {
    kvs := map[string]string{
        "a": "apple",
        "b": "banana",
    }
    for k, v := range kvs {
        fmt.Printf("%s -> %s\n", k, v)
    }
}

请注意,Go中的映射(map)没有特定的顺序,所以你可能会在另一个键值对之前得到任意的键值对。

英文:

It looks like you are trying to use string formatters, which aren't supported by fmt.Println.

According to the godocs:

> Printf formats according to a format specifier

whereas

> Println formats using the default formats

The following will give the output you are trying to get:

package main

import "fmt"

func main() {
	kvs := map[string]string{
		"a": "apple",
		"b": "banana",
	}
	for k, v := range kvs {
		fmt.Printf("%s -> %s\n", k, v)
	}
}

Note that maps in Go do not have a specific ordering so you may get any arbitrary key-value pair before another.

答案2

得分: 8

你正在使用错误的打印函数。

I) 尝试将 Println 替换为 Printf,应该可以正常工作。

II) 另一种选择是先格式化字符串 s := fmt.Sprintf("a %s", "string"),然后再打印它 fmt.Println(s)

参考资料:Go by Example: String Formatting

英文:

You are using the wrong printing function.

I) Try to replace Println with Printf and it should work fine.

II) Another option is to first format the string s := fmt.Sprintf("a %s", "string") and then print it fmt.Println(s).

reference: Go by Example: String Formatting

huangapple
  • 本文由 发表于 2017年8月12日 10:15:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/45645900.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定