Getting the start of a string with Go or Python

calendar_today timer Reading time ~1 minute

Today’s tip shows how to grab the beginning of a string in both Go and Python without using regular expressions 🎉

Let’s say you have the following string: "Gopher" and you want to know if it starts with "Go" and also if it starts with "C". In Go:

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(strings.HasPrefix("Gopher", "Go"))
    fmt.Println(strings.HasPrefix("Gopher", "C"))
}

and in Python:

print('Gopher'.startswith('Go'))
print('Gopher'.startswith('C'))

Both examples will print “true” for the first and “false” for the second in both languages.

Funnily enough, if you want to know whether your string starts with "" (empty string), both languages will return “true” too.

In Go:

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(strings.HasPrefix("Gopher", ""))
}

In Python:

print('Gopher'.startswith(''))

Important to know this so you can either avoid edge cases or step into them on purpose.

Cool right? Off to learn other languages 😜


Acknowledgments

Thanks especially to Cesar who has patiently been teaching me Go.

animated jess' signature

Related Articles