Golang: Print String

By Xah Lee. Date: . Last updated: .

Print One Byte in String

When you use a string index, e.g. "abc"[0], the value is a byte.

You may print it as hexadecimal, or integer (unicode codepoint), or as a char.

Example:

package main

import "fmt"

// ways to print 1 byte in string

func main() {

	var x = "abc"

	fmt.Printf("%#v\n", x[0]) // 0x61
	fmt.Printf("%d\n", x[0])  // 97
	fmt.Printf("%q\n", x[0])  // 'a'

}

Note, a index in string may not be a valid character.

package main

import "fmt"

// a index in string may not be a valid character

func main() {

	// utf8 encoding for FACE WITH TEARS OF JOY char is 4 bytes: F0 9F 98 82
	var y = "šŸ˜‚"

	// print 1st byte
	fmt.Printf("%#v\n", y[0]) // 0xf0
	fmt.Printf("%d\n", y[0])  // 240
	fmt.Printf("%q\n", y[0])  // 'Ć°'

}

Print Whole String

Because string is byte sequence, sometimes you want to:

The fmt.Printf function has several verbs to help.

[see ASCII Table]

package main

import "fmt"

func main() {
	var x = "ā™„\tšŸ˜‚" // with a tab (U+0009) in middle

	fmt.Printf("%s\n", x)  // ā™„ šŸ˜‚
	fmt.Printf("%q\n", x)  // "ā™„\tšŸ˜‚"
	fmt.Printf("%+q\n", x) // "\u2665\t\U0001f602"
	fmt.Printf("% x\n", x) // e2 99 a5 09 f0 9f 98 82

}

Print String in Unicode Notation

To print string in unicode notation U+2665 U+0009 U+1F602

first convert the string into rune slice, then print it with %U

example:

fmt.Printf("%U\n", []rune(x)) // [U+2665 U+0009 U+1F602]

package main

import "fmt"

func main() {
	// with a tab (U+0009) in middle
	var x = "ā™„\tšŸ˜‚"

	// turn the string into rune slice, then print it with %U
	fmt.Printf("%U\n", []rune(x)) // [U+2665 U+0009 U+1F602]
}

If you have a question, put $5 at patreon and message me.

Golang

  1. Compile, Run
  2. Source Encoding
  3. Package, Import
  4. Comment
  5. Print
  6. String
  7. String Functions
  8. Print String
  9. String Backslash Escape
  10. Rune
  11. Variable
  12. Zero Value
  13. Constant
  14. If Then Else
  15. Switch/Case
  16. Loop
  17. Basic Types
  18. Array
  19. Slice
  20. Map
  21. Struct
  22. Function
  23. Closure
  24. Pointer
  25. String, Byte Slice, Rune Slice
  26. regexp
  27. Read File
  28. Write to File
  29. Walk Dir
  30. Check File Exist
  31. System Call
  32. Get Script Path
  33. Defer
  34. Random Number

Examples

  1. Match Any Regexp
  2. Find Replace
  3. Validate Links
  4. Generate Sitemap

Reference

  1. Go Spec