Go 문자열을 인쇄하지 않고 포맷하시겠습니까?
Go에서 문자열을 인쇄하지 않고 포맷하는 간단한 방법이 있나요?
할 수 있는 일:
bar := "bar"
fmt.Printf("foo: %s", bar)
하지만 더 조작할 수 있도록 인쇄가 아닌 포맷된 문자열을 반환해 주셨으면 합니다.
다음과 같은 것도 할 수 있습니다.
s := "foo: " + bar
그러나 포맷 문자열이 복잡하고, 하나 또는 많은 부분이 문자열이 아니어서 먼저 변환해야 하는 경우에는 읽기 어려워집니다.
i := 25
s := "foo: " + strconv.Itoa(i)
더 간단한 방법은 없나요?
Sprintf가 당신이 찾고 있는 것입니다.
예
fmt.Sprintf("foo: %s", bar)
또한 "A Tour of Go"의 일부로 오류 예에서 사용 중인 것을 볼 수 있습니다.
return fmt.Sprintf("at %v, %s", e.When, e.What)
1. 심플한 스트링
「심플」한 문자열(통상은 행에 들어가는 것)의 경우, 가장 심플한 솔루션은 및 친구()fmt.Sprint()를 사용합니다.이러한 기능은 스타터가 없는 기능과 유사합니다.S 단, 이 '''는,Sxxx()를 variant로 합니다.string표준 출력으로 출력하는 대신.
예를 들어 다음과 같습니다.
s := fmt.Sprintf("Hi, my name is %s and I'm %d years old.", "Bob", 23)
''s하다
Hi, my name is Bob and I'm 23 years old.
힌트: 다른 유형의 값만 연결하려는 경우 자동으로 를 사용할 필요가 없습니다.Sprintf() 문자열이 는 ('포맷 문자열로 지정합니다.Sprint()정확히 이렇게 해.이치노
i := 23
s := fmt.Sprint("[age:", i, "]") // s will be "[age:23]"
「」만 .strings, 커스텀 구분 기호를 지정할 수도 있습니다.string(어느쪽이든)
바둑 놀이터에서 먹어보세요.
2. 복잡한 문자열(문서)
이 더 경우( """ "" " " " " " " " " " " " " " " " ) 。fmt.Sprintf()가독성과 효율성이 저하됩니다(특히 이 작업을 여러 번 수행해야 하는 경우).
이를 위해 표준 라이브러리는 및 패키지를 제공합니다.이러한 패키지는 텍스트 출력을 생성하기 위한 데이터 기반 템플릿을 구현합니다. html/template코드 주입으로부터 안전한 HTML 출력을 생성하기 위한 것입니다. 「」와 합니다.text/template '아까보다'가 아니라 '아까보다'를 .text/template.
「 」의 template으로 "을 "" .stringvalue이름만 및value를 할 때 및 할 수 (이 파일 이름만 제공).
스태틱 템플릿에 포함되어 있거나 대체되어 출력 생성 프로세스를 제어하는 파라미터를 지정할 수 있습니다.이러한 파라미터의 일반적인 형식은 다음과 같습니다.struct §map값이 중첩될 수 있습니다.
예:
예를 들어 다음과 같은 전자 메일 메시지를 생성하려고 합니다.
Hi [name]!
Your account is ready, your user name is: [user-name]
You have the following roles assigned:
[role#1], [role#2], ... [role#n]
다음과 같은 전자 메일 메시지 본문을 생성하려면 다음과 같은 정적 템플릿을 사용할 수 있습니다.
const emailTmpl = `Hi {{.Name}}!
Your account is ready, your user name is: {{.UserName}}
You have the following roles assigned:
{{range $i, $r := .Roles}}{{if $i}}, {{end}}{{.}}{{end}}
`
그리고 이를 실행하기 위한 다음과 같은 데이터를 제공합니다.
data := map[string]interface{}{
"Name": "Bob",
"UserName": "bob92",
"Roles": []string{"dbteam", "uiteam", "tester"},
}
보통 템플릿의 출력은 에 쓰이기 때문에 결과를 원하는 경우string작성 및 기입(를 실장)io.Writer 실행 및 ( ).string:
t := template.Must(template.New("email").Parse(emailTmpl))
buf := &bytes.Buffer{}
if err := t.Execute(buf, data); err != nil {
panic(err)
}
s := buf.String()
이것에 의해, 예상되는 출력이 됩니다.
Hi Bob!
Your account is ready, your user name is: bob92
You have the following roles assigned:
dbteam, uiteam, tester
바둑 놀이터에서 시도해 보세요.
Go 1. 1.10, Go 1.10, Dada, Dama, Dama, Damna, Damna, Damna, Damna, Damna, Damna, Damna, Damna, Damna, Damnamna, Damnamnamnamnamnamnamnamnamnamnamnamnamnamnamnamnamnamnamnamnamnamnamnamnamnamnambytes.Buffer즉, 용도는 매우 유사합니다.
builder := &strings.Builder{}
if err := t.Execute(builder, data); err != nil {
panic(err)
}
s := builder.String()
바둑판에서 한번 써보세요.
템플릿 실행 결과는 다음과 같습니다.os.Stdout)io.Writer
t := template.Must(template.New("email").Parse(emailTmpl))
if err := t.Execute(os.Stdout, data); err != nil {
panic(err)
}
이렇게 하면 결과가 직접 에 기록됩니다.os.Stdout바둑판에서 한번 해보세요.
를 Sprintf(); 이 이것 좀 봐
package main
import "fmt"
func main() {
address := "NYC"
fmt.Sprintf("I live in %v", address)
}
이 코드를 실행하면 아무것도 출력되지 않습니다., ""를 에는"""""""""""""Sprintf()미래 목적으로 사용할 수 있습니다.
package main
import "fmt"
func main() {
address := "NYC"
fmt.Sprintf("I live in %v", address)
var city = fmt.Sprintf("lives in %v", address)
fmt.Println("Michael",city)
}
템플릿에서 문자열 포맷을 위한 go 프로젝트를 만들었습니다(C# 또는 Python 스타일로 문자열을 포맷할 수 있습니다). 성능 테스트에서는 fmt보다 빠릅니다.Sprintf, https://github.com/Wissance/stringFormatter에서 찾을 수 있습니다.
다음과 같이 동작합니다.
func TestStrFormat(t *testing.T) {
strFormatResult, err := Format("Hello i am {0}, my age is {1} and i am waiting for {2}, because i am {0}!",
"Michael Ushakov (Evillord666)", "34", "\"Great Success\"")
assert.Nil(t, err)
assert.Equal(t, "Hello i am Michael Ushakov (Evillord666), my age is 34 and i am waiting for \"Great Success\", because i am Michael Ushakov (Evillord666)!", strFormatResult)
strFormatResult, err = Format("We are wondering if these values would be replaced : {5}, {4}, {0}", "one", "two", "three")
assert.Nil(t, err)
assert.Equal(t, "We are wondering if these values would be replaced : {5}, {4}, one", strFormatResult)
strFormatResult, err = Format("No args ... : {0}, {1}, {2}")
assert.Nil(t, err)
assert.Equal(t, "No args ... : {0}, {1}, {2}", strFormatResult)
}
func TestStrFormatComplex(t *testing.T) {
strFormatResult, err := FormatComplex("Hello {user} what are you doing here {app} ?", map[string]string{"user":"vpupkin", "app":"mn_console"})
assert.Nil(t, err)
assert.Equal(t, "Hello vpupkin what are you doing here mn_console ?", strFormatResult)
}
이 경우 형식 문자열에 Sprintf()를 사용해야 합니다.
func Sprintf(format string, a ...interface{}) string
Sprintf는 형식 지정자에 따라 형식을 지정하고 결과 문자열을 반환합니다.
s := fmt.Sprintf("Good Morning, This is %s and I'm living here from last %d years ", "John", 20)
출력은 다음과 같습니다.
안녕하세요, 저는 존이고 지난 20년간 여기에 살고 있습니다.
fmt.SprintF을 "예"와 할 수 .fmt.PrintF
에러 문자열을 포맷하는 방법을 찾고 있습니다. 같은 이 필요한 '어울리다'를 하세요.fmt.Errorf()★★★★★★ 。
는 " " " 입니다.func Errorf(format string, a ...interface{}) error. 은 를 error인터페이스입니다.
상세한 것에 대하여는, https://golang.org/pkg/fmt/#Errorf 를 참조해 주세요.
「 」를 하는 대신에, 「 」를 사용합니다.template.New 돼요.new템플릿에 내장되어 있습니다.템플릿:
package main
import (
"strings"
"text/template"
)
func format(s string, v interface{}) string {
t, b := new(template.Template), new(strings.Builder)
template.Must(t.Parse(s)).Execute(b, v)
return b.String()
}
func main() {
bar := "bar"
println(format("foo: {{.}}", bar))
i := 25
println(format("foo: {{.}}", i))
}
언급URL : https://stackoverflow.com/questions/11123865/format-a-go-string-without-printing
'programing' 카테고리의 다른 글
| SQL Server의 모든 테이블을 검색하여 문자열 찾기 (0) | 2023.04.20 |
|---|---|
| Git에서 최신 로컬 커밋을 취소하려면 어떻게 해야 하나요? (0) | 2023.04.15 |
| 빈 디렉터리 찾기 (0) | 2023.04.15 |
| Android-Facebook 앱의 주요 해시 (0) | 2023.04.15 |
| 대소문자를 구분하지 않는 'Contains(string)' (0) | 2023.04.15 |