Back to Blog

Strings & Formatting (Printf, strings Package, Slicing) - Go Tutorial for Beginners #3

Sandy LaneSandy Lane

Video: Strings & Formatting (Printf, strings Package, Slicing) - Go Tutorial for Beginners #3 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Strings & Formatting in Go: Printf, strings Package, and Slicing

Working with strings is fundamental in Go programming. This guide covers string creation, concatenation, formatted printing using fmt.Printf, useful functions from the strings package, and accessing or slicing strings by index.

Code

package main

import (
  "fmt"
  "strings"
)

func main() {
  // String concatenation
  greeting := "Hello"
  name := "World"
  message := greeting + ", " + name + "!"
  fmt.Println(message) // Output: Hello, World!

  // Printf formatting with verbs
  age := 30
  price := 12.3456
  fmt.Printf("Name: %s\n", name)           // %s for string
  fmt.Printf("Age: %d years\n", age)        // %d for integers
  fmt.Printf("Price: $%.2f\n", price)       // %.2f for float with 2 decimals
  fmt.Printf("Type: %T, Value: %v\n", age, age) // %T for type, %v for value

  // Using strings package functions
  upper := strings.ToUpper("hello")         // "HELLO"
  trimmed := strings.TrimSpace("  hi  ")    // "hi"
  parts := strings.Split("a,b,c", ",")      // []string{"a", "b", "c"}
  joined := strings.Join(parts, "-")        // "a-b-c"
  fmt.Println(upper, trimmed, parts, joined)

  // String indexing and slicing
  word := "Golang"
  firstChar := word[0]                       // byte value of 'G'
  firstTwo := word[:2]                       // "Go"
  fromIndex2 := word[2:]                     // "lang"
  middle := word[1:5]                        // "olan"

  fmt.Printf("First char: %c\n", firstChar) // %c to print character
  fmt.Println("First two letters:", firstTwo)
  fmt.Println("From index 2:", fromIndex2)
  fmt.Println("Middle portion:", middle)
}

Key Points

  • Use double quotes for string literals and the + operator to concatenate strings.
  • fmt.Printf format verbs like %s, %d, %f, %v, and %T provide precise control over output formatting.
  • The strings package offers handy functions such as ToUpper, TrimSpace, Split, and Join for common string operations.
  • Strings can be indexed and sliced using square brackets, similar to arrays, to access substrings or individual characters.
  • Remember that indexing a string returns a byte, so use %c in Printf to print it as a character.