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 😜
Links
- Python str.startswith
- Go strings.HasPrefix
- Implementation of strings.HasPrefix
- If you want to see Cesar explaining all of this in a video, check out this post from the Go study group
Acknowledgments
Thanks especially to Cesar who has patiently been teaching me Go.