All Go Rust Python PHP JavaScript
Chrome Dev Summit to secure your spot in workshops, office hours and learning lounges!

Hello World in Rust

In Rust, "Hello World!" is the first basic program. Build and Run In our main.rs, add the following code: // main.rs fn main() { println!("Hello,世界,こんにちは,안녕하세요") } Hello,世界,こんにちは,안녕하세요 we can run our application by typing: Build rustc main.rs ./main Hello,世界,こんにちは,안녕하세요 Using cargo Command Generating a new project To start, we’ll use Cargo to make a new project for us. For example, cargo cargo new hello-rust Created binary (application) `hello-rust` package This will generate a new directory called hello-rust with the following files: hello-rust |- Cargo.toml #is the manifest file for Rust. |- src |- main.rs #is where we’ll write our application code. Run this program We can run this program by moving into the new directory that we made and running this in our terminal: cargo cd hello-rust cargo run Compiling hello-rust v0.1.0 (/home/rust/hello-rust) Finished dev [unoptimized + debuginfo] target(s) in 2.68s Running `target/debug/hello-rust` Hello, world! Hello fellow Rustaceans! A small Rust application. For example, use ferris_says::say; // from the previous step use std::io::{stdout, BufWriter}; fn main() { let stdout = stdout(); let message = String::from("Hello fellow Rustaceans!"); let width = message.chars().count(); let mut writer = BufWriter::new(stdout.lock()); say(message.as_bytes(), width, &mut writer).unwrap(); } Run this program: cargo cargo run __________________________ -------------------------- \ \ _~^~^~_ \) / o o \ (/ '_ - _' / '-----' \
pooriabt

How To Install Rust in Linux

In Rust, there are two ways to install rust in Linux. Running the following in your terminal If you’re running macOS, Linux, or another Unix-like OS. To download Rustup and install Rust, run the following in your terminal, then follow the on-screen instructions. curl curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh Rust is installed now. Great! To get started you may need to restart your current shell. This would reload your PATH environment variable to include Cargo's bin directory ($HOME/.cargo/bin). To configure your current shell, run: source $HOME/.cargo/env To configure your current shell, run: Rust source ~/.profile source ~/.cargo/env rustc --version cargo --version rustc 1.60.0 (7737e0b5c 2022-04-04) cargo 1.60.0 (d1fd9fe 2022-03-01) When you install Rustup you’ll also get the latest stable version of the Rust build tool and package manager, also known as Cargo. On Windows, download and run rustup-init.exe. Standalone installers The official Rust standalone installers contain a single release of Rust, and are suitable for offline installation. See: https://forge.rust-lang.org/infra/other-installation-methods.html Try Rust Online You can try Rust online in the Rust Playground without installing anything on your computer. See: TRY RUST WITHOUT INSTALLING Rustc Help Commands and Options Usage: rustc [OPTIONS] INPUT OPTIONS: ##### -h, --help Display this message ##### --cfg SPEC Configure the compilation environment ##### -L [KIND=]PATH Add a directory to the library search path. The optional KIND can be one of dependency, crate, native, framework, or all (the default). ##### -l [KIND[:MODIFIERS]=]NAME[:RENAME] Link the generated crate(s) to the specified native library NAME. The optional KIND can be one of static, framework, or dylib (the default). Optional comma separated MODIFIERS (bundle|verbatim|whole-archive|as-needed) may be specified each with a prefix of either '+' to enable or '-' to disable. ##### --crate-type [bin|lib|rlib|dylib|cdylib|staticlib|proc-macro] Comma separated list of types of crates for the compiler to emit ##### --crate-name NAME Specify the name of the crate being built ##### --edition 2015|2018|2021 Specify which edition of the compiler to use when compiling code. ##### --emit [asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info|mir] Comma separated list of types of output for the compiler to emit ##### --print [crate-name|file-names|sysroot|target-libdir|cfg|target-list|target-cpus|target-features|relocation-models|code-models|tls-models|target-spec-json|native-static-libs|stack-protector-strategies|link-args] Compiler information to print on stdout ##### -g Equivalent to -C debuginfo=2 ##### -O Equivalent to -C opt-level=2 ##### -o FILENAME Write output to filename ##### --out-dir DIR Write output to compiler-chosen filename in dir ##### --explain OPT Provide a detailed explanation of an error message ##### --test Build a test harness ##### --target TARGET Target triple for which the code is compiled ##### -A, --allow LINT Set lint allowed ##### -W, --warn LINT Set lint warnings ##### --force-warn LINT Set lint force-warn ##### -D, --deny LINT Set lint denied ##### -F, --forbid LINT Set lint forbidden ##### --cap-lints LEVEL Set the most restrictive lint level. More restrictive lints are capped at this level ##### -C, --codegen OPT[=VALUE] Set a codegen option ##### -V, --version Print version info and exit ##### -v, --verbose Use verbose output Cargo Help Commands and Options Rust's package manager USAGE: cargo [+toolchain] [OPTIONS] [SUBCOMMAND] OPTIONS: ##### -V, --version Print version info and exit ##### --list List installed commands ##### --explain <CODE> Run `rustc --explain CODE` ##### -v, --verbose Use verbose output (-vv very verbose/build.rs output) ##### -q, --quiet Do not print cargo log messages ##### --color <WHEN> Coloring: auto, always, never ##### --frozen Require Cargo.lock and cache are up to date ##### --locked Require Cargo.lock is up to date ##### --offline Run without accessing the network ##### --config <KEY=VALUE> Override a configuration value (unstable) ##### -Z <FLAG> Unstable (nightly-only) flags to Cargo, see 'cargo -Z help' for details ##### -h, --help Print help information ######## Commands: Some common cargo commands are (see all commands with --list): ##### build, b Compile the current package ##### check, c Analyze the current package and report errors, but don't build object files ##### clean Remove the target directory ##### doc, d Build this package's and its dependencies' documentation ##### new Create a new cargo package ##### init Create a new cargo package in an existing directory ##### run, r Run a binary or example of the local package ##### test, t Run the tests ##### bench Run the benchmarks ##### update Update dependencies listed in Cargo.lock ##### search Search registry for crates ##### publis Package and upload this package to the registry ##### install Install a Rust binary. Default location is $HOME/.cargo/bin ##### uninstall Uninstall a Rust binary See 'cargo help <command>' for more information on a specific command.
pooriabt

How to find the type of an object in Go

In Golang, there are three ways to find the type of an object. Using fmt.Sprintf Function You can use fmt.Sprintf function to get a string representation. For example, package main import "fmt" func main() { i := 10 f := 2.0 var m map[string]int s := fmt.Sprintf("%T", i) fmt.Printf("%q\n", s) s = fmt.Sprintf("%T", f) fmt.Printf("%q\n", s) s = fmt.Sprintf("%T", m) fmt.Printf("%q\n", s) } "int" "float64" "map[string]int" %T a Go-syntax representation of the type of the value Using reflect.TypeOf Function TypeOf returns the reflection Type that represents the dynamic type of i. package main import ( "fmt" "reflect" ) func main() { i := 10 f := 2.0 var m map[string]int s := reflect.TypeOf(i).String() fmt.Printf("%q\n", s) s = reflect.TypeOf(f).String() fmt.Printf("%q\n", s) s = reflect.TypeOf(m).String() fmt.Printf("%q\n", s) s = reflect.TypeOf(m).Kind().String() fmt.Printf("%q\n", s) } "int" "float64" "map[string]int" "map" bug_reportreflect.TypeOf - gives type along with the package name. bug_reportreflect.TypeOf().Kind() - gives underlining type. Using Type Assertions The primary expression x.(T). For example, package main import ( "fmt" ) func Typeof(v interface{}) string { switch v.(type) { case int: return "int" case float64: return "float64" // ... etc default: return "unknown" } } func main() { i := 10 f := 2.0 s := Typeof(i) fmt.Printf("%q\n", s) s = Typeof(f) fmt.Printf("%q\n", s) } "int" "float64" Based on a barebones benchmark, the reflect approach is surprisingly more efficient.
Patcher56

How to get the first and last day of the current month in Go

In Golang, there are two ways to get the start and end date of the current month. Using time.AddDate Function AddDate returns the time corresponding to adding the given number of years, months, and days to t. For example, package main import ( "fmt" "time" ) func main() { t := time.Now() // format := "2006-01-02 15:04:05" // t, _ = time.Parse(format, "2022-02-05 12:00:00") // the first day firstOfMonth := t.AddDate(0, 0, -t.Day()+1) s := firstOfMonth.Format(time.RFC3339) fmt.Println(s) // the last day lastOfMonth := t.AddDate(0, 1, -t.Day()) s = lastOfMonth.Format(time.RFC3339) fmt.Println(s) } 2022-04-01T09:19:25+09:00 2022-04-30T09:19:25+09:00 By far, this is the most elegant approach. If time, DST and such are important, it should be pretty straightforward to ornament those details on top of it once you get the date. Using time.Date Function You can use time.Date function, it really simple. For example, package main import ( "fmt" "time" ) func main() { t := time.Now() y, m, _ := t.Date() loc := t.Location() // the first day firstOfMonth := time.Date(y, m, 1, 0, 0, 0, 0, loc) s := firstOfMonth.Format(time.RFC3339) fmt.Println(s) // the last day lastOfMonth := time.Date(y, m+1, 1, 0, 0, 0, -1, loc) s = lastOfMonth.Format(time.RFC3339) fmt.Println(s) } 2022-04-01T00:00:00+08:00 2022-04-30T23:59:59+08:00 The month, day, hour, min, sec, and nsec values may be outside their usual ranges and will be normalized during the conversion. For example, October 32 converts to November 1.
Tomoki

How to format a date or time in Go

In Golang, there are two ways to format the time. The layout string Go doesn’t use yyyy-mm-dd layout to format a time. Instead, you format a special layout parameter. 2006-01-02 15:04:05.999999999 -0700 MST package main import ( "fmt" "time" ) func main() { // format current time s := time.Now().Format("2006-01-02 15:04:05") fmt.Println(s) // RFC3339 s = time.Now().Format(time.RFC3339) fmt.Println(s) } 2022-04-18 13:24:09 2022-04-18T13:24:09+09:00 The time package in the Golang standard library contains a bunch of useful constants that are used for formatting time. const ( ANSIC = "Mon Jan _2 15:04:05 2006" UnixDate = "Mon Jan _2 15:04:05 MST 2006" RubyDate = "Mon Jan 02 15:04:05 -0700 2006" RFC822 = "02 Jan 06 15:04 MST" RFC822Z = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone RFC850 = "Monday, 02-Jan-06 15:04:05 MST" RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST" RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone RFC3339 = "2006-01-02T15:04:05Z07:00" RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00" Kitchen = "3:04PM" // Handy time stamps. Stamp = "Jan _2 15:04:05" StampMilli = "Jan _2 15:04:05.000" StampMicro = "Jan _2 15:04:05.000000" StampNano = "Jan _2 15:04:05.000000000" ) const ( _ = iota stdLongMonth = iota + stdNeedDate // "January" stdMonth // "Jan" stdNumMonth // "1" stdZeroMonth // "01" stdLongWeekDay // "Monday" stdWeekDay // "Mon" stdDay // "2" stdUnderDay // "_2" stdZeroDay // "02" stdUnderYearDay // "__2" stdZeroYearDay // "002" stdHour = iota + stdNeedClock // "15" stdHour12 // "3" stdZeroHour12 // "03" stdMinute // "4" stdZeroMinute // "04" stdSecond // "5" stdZeroSecond // "05" stdLongYear = iota + stdNeedDate // "2006" stdYear // "06" stdPM = iota + stdNeedClock // "PM" stdpm // "pm" stdTZ = iota // "MST" stdISO8601TZ // "Z0700" // prints Z for UTC stdISO8601SecondsTZ // "Z070000" stdISO8601ShortTZ // "Z07" stdISO8601ColonTZ // "Z07:00" // prints Z for UTC stdISO8601ColonSecondsTZ // "Z07:00:00" stdNumTZ // "-0700" // always numeric stdNumSecondsTz // "-070000" stdNumShortTZ // "-07" // always numeric stdNumColonTZ // "-07:00" // always numeric stdNumColonSecondsTZ // "-07:00:00" stdFracSecond0 // ".0", ".00", ... , trailing zeros included stdFracSecond9 // ".9", ".99", ..., trailing zeros omitted stdNeedDate = 1 << 8 // need month, day, year stdNeedClock = 2 << 8 // need hour, minute, second stdArgShift = 16 // extra argument in high bits, above low stdArgShift stdMask = 1<<stdArgShift - 1 // mask out argument ) There's no such thing as stdZeroHour, so no alternative behaviour for stdHour. In Golang 1.17+ for fraction of seconds (.999 or .000) you can use , instead of . (,999 or ,000) but output is always with . Using fmt.Sprintf Function For example, to get the current date time as "yyyy-MM-dd HH:mm:ss", you can use these methods with fmt.Sprintf: package main import ( "fmt" "time" ) func main() { // format yyyy-MM-dd HH:mm:ss t := time.Now() s := fmt.Sprintf("%d-%02d-%02d %02d:%02d:%02d", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second()) fmt.Println(s) } 2022-04-18 13:34:02 This method isn't very effective. For 3-letter months, it does not work.
aweis

How to check if a map is empty in Go

2 ways to check if a map is empty in Golang. Using len Function You can use the len function to check if a map is empty. it returns the length of v, according to its type. len(s) map[K]T: map length (number of defined keys) package main import "fmt" func main() { m := map[string]int{} // Do if len(m) == 0 { // map is empty fmt.Println("Empty!") } // Don’t if m == nil { // m != nil fmt.Println("nil Empty!") } } Empty! Using nil Identifier nil is a predeclared identifier in Go. you can use nil to check if the map[string]int has been initialised. package main import "fmt" func main() { // not assigned any value var m map[string]int // Do if len(m) == 0 { fmt.Println("Empty!") } // Don’t if m == nil { fmt.Println("nil Empty!") } m = map[string]int{} // Don’t if m == nil { // m != nil fmt.Println("nil Empty!") } } Empty! nil Empty! You can't use that to check if the map is empty.
Tomoki

How to convert an int to a string type in Go

3 ways to convert int64 to string in Golang. Using strconv.Itoa Function The code snippet below shows how to convert an int to a string using the Itoa function. package main import ( "fmt" "strconv" ) func main() { s := strconv.Itoa(100) fmt.Printf("%q\n", s) } "100" Warning: If we use plain int to string conversion, the integer value is interpreted as a Unicode code point. And the resulting string will contain the character represented by the code point, encoded in UTF-8. // conversion from untyped int to string yields a string of one rune, not a string of digits (did you mean fmt.Sprint(x)?) s := string(100) // "d" "d" Using strconv.FormatInt Function FormatInt returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z' for digit values >= 10. Converting int64 to string. For example, package main import ( "fmt" "strconv" ) func main() { var n int64 = 108 // Decimal s := strconv.FormatInt(n, 10) fmt.Printf("%q\n", s) // Binary s = strconv.FormatInt(n, 2) fmt.Printf("%q\n", s) // Hexadecimal s = strconv.FormatInt(n, 16) // "6c" fmt.Printf("%q\n", s) } "108" "1101100" "6c" Using fmt.Sprintf Function The fmt.Sprintf function is a useful general tool for converting data to string: package main import ( "fmt" ) func main() { var n int64 = 14 s := fmt.Sprintf("%03d", n) fmt.Printf("%q\n", s) } "014" The verbs Go offers several printing “verbs” designed to format general Go values. The verbs: ##### %v the value in a default format when printing structs, the plus flag (%+v) adds field names ##### %#v a Go-syntax representation of the value ##### %T a Go-syntax representation of the type of the value ##### %% a literal percent sign; consumes no value ##### %t the word true or false ##### %b base 2 ##### %c the character represented by the corresponding Unicode code point ##### %d base 10 ##### %o base 8 ##### %O base 8 with 0o prefix ##### %q a single-quoted character literal safely escaped with Go syntax. ##### %x base 16, with lower-case letters for a-f ##### %X base 16, with upper-case letters for A-F ##### %U Unicode format: U+1234; same as "U+%04X" ##### %b decimalless scientific notation with exponent a power of two, in the manner of strconv.FormatFloat with the 'b' format, e.g. -123456p-78 ##### %e scientific notation, e.g. -1.234456e+78 ##### %E scientific notation, e.g. -1.234456E+78 ##### %f decimal point but no exponent, e.g. 123.456 ##### %F synonym for %f ##### %g %e for large exponents, %f otherwise. Precision is discussed below. ##### %G %E for large exponents, %F otherwise ##### %x hexadecimal notation (with decimal power of two exponent), e.g. -0x1.23abcp+20 ##### %X upper-case hexadecimal notation, e.g. -0X1.23ABCP+20 ##### %s the uninterpreted bytes of the string or slice ##### %q a double-quoted string safely escaped with Go syntax ##### %x base 16, lower-case, two characters per byte ##### %X base 16, upper-case, two characters per byte ##### %f default width, default precision ##### %9f width 9, default precision ##### %.2f default width, precision 2 ##### %9.2f width 9, precision 2 ##### %9.f width 9, precision 0 ##### + always print a sign for numeric values; guarantee ASCII-only output for %q (%+q) ##### - pad with spaces on the right rather than the left (left-justify the field) ##### # alternate format: add leading 0b for binary (%#b), 0 for octal (%#o), 0x or 0X for hex (%#x or %#X); suppress 0x for %p (%#p); for %q, print a raw (backquoted) string if strconv.CanBackquote returns true; always print a decimal point for %e, %E, %f, %F, %g and %G; do not remove trailing zeros for %g and %G; write e.g. U+0078 'x' if the character is printable for %U (%#U). ##### ' ' (space) leave a space for elided sign in numbers (% d); put spaces between bytes printing strings or slices in hex (% x, % X) ##### 0 pad with leading zeros rather than spaces; for numbers, this moves the padding after the sign
aweis

How to to create a multiline string in Python

4 ways to create multiple lines string in Python. Using triple-quotes String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. End of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line. The following example: #!/usr/bin/env python3 str = """\ Usage: python [OPTIONS] -h Display -H host Hostname """ print(str) Usage: python [OPTIONS] -h Display -H host Hostname Using Brackets List comprehensions provide a concise way to create lists. For example, #!/usr/bin/env python3 sql = ("SELECT " "id, name " "FROM user") print(sql) # newline sql = ("SELECT \n" "id, name \n" "FROM user") print(sql) SELECT id, name FROM user SELECT id, name FROM user Using Backslash Adding a \ at the end of the line. For example, #!/usr/bin/env python3 sql = "SELECT " \ "id, name " \ "FROM user" print(sql) SELECT id, name FROM user Using join Method The final approach is applying the string join() function to convert a string into multiline. For example, #!/usr/bin/env python3 sql = ''.join("SELECT " "id, name " "FROM user") print(sql) SELECT id, name FROM user
aweis

How to fill a list with same values in Python

3 ways to initialize a Python Array . Initialize a list with values If you want to initialize a list of any number of elements where all elements are filled with any values, you can use the * operator as follows. #!/usr/bin/env python3 arr = ['H'] * 5 print(arr) ['H', 'H', 'H', 'H', 'H'] Our program has created a list that contains 5 values. Using List Comprehensions List comprehensions provide a concise way to create lists. For example, #!/usr/bin/env python3 arr = ['H' for x in range(5)] print(arr) arr = [x**2 for x in range(5)] print(arr) ['H', 'H', 'H', 'H', 'H'] [0, 1, 4, 9, 16] Using NumPy Module NumPy is the fundamental package for scientific computing in Python. numpy.full return a new array of given shape and type, filled with fill_value. #!/usr/bin/env python3 # Import module import numpy as np arr = np.full(5, 'H') print(arr) # a tuple arr = np.full((2, 2), 'H') print(arr) ['H' 'H' 'H' 'H' 'H'] [['H' 'H'] ['H' 'H']]
aweis

How to delete an element from a slice in Go

Removing a string from a slice in Golang. Faster Version If you do not care about ordering, you have the much faster possibility to replace the element to delete with the one at the end of the slice and then return the n-1 first elements: package main import "fmt" func Remove(s []string, i int) []string { if len(s) == 0 { return s } if i == 0 { return s[1:] } if i == len(s)-1 { return s[:len(s)-1] } s[i] = s[len(s)-1] return s[:len(s)-1] } func main() { s := []string{"a", "b", "c", "d", "e", "f"} a := Remove(s, 2) fmt.Printf("%q\n", a) s = []string{"a", "b", "c", "d", "e", "f"} a = Remove(s, 0) fmt.Printf("%q\n", a) s = []string{"a", "b", "c", "d", "e", "f"} a = Remove(s, 5) fmt.Printf("%q\n", a) } ["a" "b" "f" "d" "e"] ["b" "c" "d" "e" "f"] ["a" "b" "c" "d" "e"] if i >= len(s), will cause Go to panic. panic: runtime error: index out of range [20] with length 6. Using append Function If you want to keep your array ordered, you have to shift all of the elements at the right of the deleting index by one to the left. Hopefully, this can be done easily in Golang: package main import "fmt" func Remove(s []string, i int) []string { return append(s[:i], s[i+1:]...) } func main() { s := []string{"a", "b", "c", "d", "e", "f"} a := Remove(s, 2) fmt.Printf("%q\n", a) } ["a" "b" "d" "e" "f"] However, this is inefficient because you may end up with moving all of the elements, which is costly. Using copy Function For example, package main import "fmt" func Remove(s []string, i int) []string { copy(s[i:], s[i+1:]) return s[:len(s)-1] } func main() { s := []string{"a", "b", "c", "d", "e", "f"} a := Remove(s, 2) fmt.Printf("%q\n", a) } ["a" "b" "d" "e" "f"] The code copies len(a) - i - 1 elements and runs in linear time.
pooriabt

How to shuffle a slice in Go

Shuffling a Slice in Golang. Using rand.Shuffle Function Shuffle pseudo-randomizes the order of elements using the default Source. package main import ( "fmt" "math/rand" "time" ) func main() { s := []string{"Japan", "Germany", "France"} rand.Seed(time.Now().UnixNano()) // func Shuffle(n int, swap func(i, j int)) rand.Shuffle(len(s), func(i, j int) { s[i], s[j] = s[j], s[i] }) fmt.Printf("%q\n", s) } ["Japan" "France" "Germany"] Don't forget about the rand.Seed(), otherwise you got the same string every first time launch. n is the number of elements. Shuffle panics if n < 0. swap swaps the elements with indexes i and j. Using rand.Intn Function Use the rand.Seed and rand.Intn functions in package math/rand. Fisher–Yates algorithm: package main import ( "fmt" "math/rand" "time" ) func main() { s := []string{"Japan", "Germany", "France"} rand.Seed(time.Now().UnixNano()) for i := len(s) - 1; i > 0; i-- { j := rand.Intn(i + 1) s[i], s[j] = s[j], s[i] } fmt.Printf("%q\n", s) } ["France" "Germany" "Japan"] Intn returns, as an int, a non-negative pseudo-random number in [0,n) It panics if n <= 0.
ada

How to reverse a slice in Go

Reverse a Slice in Golang. Using a for Loop The standard library does not have a built-in function for reversing a slice. Use a for loop to reverse a slice: package main import "fmt" func main() { s := []string{"b", "c", "d"} for i := len(s)/2 - 1; i >= 0; i-- { s[i], s[len(s)-1-i] = s[len(s)-1-i], s[i] } fmt.Printf("%q\n", s) } ["d" "c" "b"] The same thing, except with two indices: package main import "fmt" func main() { s := []string{"b", "c", "d"} for l, r := 0, len(s)-1; l < r; l, r = l+1, r-1 { s[l], s[r] = s[r], s[l] } fmt.Printf("%q\n", s) } ["d" "c" "b"] Using reflect.Swapper Function Use reflect.Swapper to write a function that works with arbitrary slice types in Go version 1.8 or later: package main import ( "fmt" "reflect" ) func main() { s := []string{"b", "c", "d"} n := reflect.ValueOf(s).Len() swap := reflect.Swapper(s) for i, j := 0, n-1; i < j; i, j = i+1, j-1 { swap(i, j) } fmt.Printf("%q\n", s) } ["d" "c" "b"] The functions in this answer reverse the slice inplace. If you do not want to modify the original slice, copy the slice before reversing the slice. Using Type Parameters Use type parameters to write a generic reverse function in Go 1.18 or later: func Reverse[S ~[]E, E any](s S) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } }
ada

How to split a string into a slice in Go

Splitting a String into a Slice in Golang. Using strings.Split Function Use the strings.Split function to split a string into its comma separated values. package main import ( "fmt" "strings" ) func main() { s := "Japan,Germany" // func Split(s, sep string) []string slice := strings.Split(s, ",") fmt.Printf("%q\n", slice) // sep is empty slice = strings.Split(s, "") fmt.Printf("%q\n", slice) } ["Japan" "Germany"] ["J" "a" "p" "a" "n" "," "G" "e" "r" "m" "a" "n" "y"] If s does not contain sep and sep is not empty, Split returns a slice of length 1 whose only element is s. If sep is empty, Split splits after each UTF-8 sequence. If both s and sep are empty, Split returns an empty slice. Using strings.Fields Function Fields splits the string s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of substrings of s or an empty slice if s contains only white space. For example, package main import ( "fmt" "strings" ) func main() { s := "Japan Germany" // var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1} // func Fields(s string) []string slice := strings.Fields(s) fmt.Printf("%q\n", slice) } ["Japan" "Germany"] Using the regexp Split Function Split slices s into substrings separated by the expression and returns a slice of the substrings between those expression matches. The count determines the number of substrings to return. if n < 0, it returns all substrings. For example, package main import ( "fmt" "regexp" ) func main() { s := "abaabaccad" a := regexp.MustCompile(`a`) // func (re *Regexp) Split(s string, n int) []string fmt.Printf("%q\n", a.Split(s, -1)) fmt.Printf("%q\n", a.Split(s, 0)) fmt.Printf("%q\n", a.Split(s, 1)) } ["" "b" "" "b" "cc" "d"] [] ["abaabaccad"] You can use regexp.Split to split a string into a slice of strings with the regex pattern as the delimiter. package main import ( "fmt" "regexp" ) func main() { s := "how789to1234split" a := regexp.MustCompile(`[0-9]+`) fmt.Printf("%q\n", a.Split(s, -1)) } ["how" "to" "split"]
Unused

How to join a slice of strings into a single string in Go

Convert Slice to String in Golang. Using strings.Join Function Converting a slice of strings to a single string is pretty easy to do in Go. The strings.Join() method is present in the standard library for this purpose, and its usage is shown below: package main import ( "fmt" "strings" ) func main() { a := []string{"United States", "Japan", "Germany"} // func Join(elems []string, sep string) string s := strings.Join(a, ",") fmt.Println(s) } United States,Japan,Germany Join concatenates the elements of its first argument to create a single string. The separator string sep is placed between elements in the resulting string. Other types For slices with ints, or other types of elements, we can first convert a slice into a string slice. For example, package main import ( "fmt" "strconv" "strings" ) func main() { // ints a := []int{1, 2, 3} slice := []string{} for _, v := range a { text := strconv.Itoa(v) slice = append(slice, text) } // func Join(elems []string, sep string) string s := strings.Join(slice, "|") fmt.Println(s) } 1|2|3 The Go blog about the differences between slices and arrays
Tomoki

How to find intersection of two slices in Go

Intersection set of golang slices. Using map cache It's a best method for intersection two slice. Time complexity is too low. Time Complexity : O(m+n) package main import "fmt" func intersection(a, b []string) ([]string, error) { // uses empty struct (0 bytes) for map values. m := make(map[string]struct{}, len(b)) // cached for _, v := range b { m[v] = struct{}{} } var s []string for _, v := range a { if _, ok := m[v]; ok { s = append(s, v) } } return s, nil } func main() { s1 := []string{"a", "b"} s2 := []string{"b", "c", "d"} // find s1 strings in s2 s, _ := intersection(s1, s2) fmt.Println(s) } [b] You can use reflect.TypeOf for any []T. Using simple loops Compare each element in A to each in B. For example, package main import "fmt" func intersection(a, b []string) ([]string, error) { var s []string for _, m := range a { ok := false for _, n := range b { if m == n { ok = true break } } if ok { s = append(s, m) } } return s, nil } func main() { s1 := []string{"a", "b"} s2 := []string{"b", "c", "d"} // find s1 strings in s2 s, _ := intersection(s1, s2) fmt.Println(s) } [b] You can then create your own package and reuse once you settle how you want to implement it. package intersection func String(a []string, b []string) (inter []string, error) func Int(a []int, b []int) (inter []int, error) func Float64(a []Float64, b []Float64) (inter []Float64, error)
Patcher56

How to fill a slice with values in Go

Filling a slice with a repeated pattern. Using for Loop Using a for loop is the simplest solution. Fill the slice with the value 8 by looping through each element and setting the value. package main import "fmt" func main() { slice := make([]int64, 10, 10) for i := 0; i < len(slice); i++ { slice[i] = 8 } fmt.Println(slice) } [8 8 8 8 8 8 8 8 8 8] Using for range For example, package main import "fmt" func main() { slice := make([]int64, 10, 10) for i := range slice { slice[i] = 8 } fmt.Println(slice) } [8 8 8 8 8 8 8 8 8 8] Using the copy trick Example of using the copy trick to fill an array/slice with a multi-element pattern. package main import "fmt" func main() { // the pattern pattern := []int64{8, 9, 10} slice := make([]int64, 10, 10) copy(slice, pattern) for i := len(pattern); i < len(slice); i *= 2 { copy(slice[i:], slice[:i]) } fmt.Println(slice) } [8 9 10 8 9 10 8 9 10 8] Using append Function The resulting value of append is a slice containing all the elements of the original slice plus the provided values. package main import "fmt" func main() { slice := []int64{} for i := 0; i < 10; i++ { slice = append(slice, 8) } fmt.Println(slice) } [8 8 8 8 8 8 8 8 8 8]
pooriabt

How to define python source code encodings

Correct way to define Python source code encoding. PEP 263 Python will default to ASCII as standard encoding if no other encoding hints are given. PEP 263 defines how to declare Python source code encoding. Using Coding To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=<encoding name> # coding=utf-8 import os, sys ... Using Formats Recognized To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: #!/usr/bin/python3 # -*- coding: <encoding name> -*- or: #!/usr/bin/python3 # vim: set fileencoding=<encoding name> : With interpreter binary and using Emacs style file encoding comment: #!/usr/bin/python3 # -*- coding: utf-8 -*- import os, sys ...
Tomoki

How to calculate CRC32 checksum in Python

Python Examples of zlib.crc32Cyclic redundancy check A cyclic redundancy check (CRC) is an error-detecting code commonly used in digital networks and storage devices to detect accidental changes to digital data. Using zlib.crc32 Function Computes a CRC (Cyclic Redundancy Check) checksum of data. The result is an unsigned 32-bit integer. If value is present, it is used as the starting value of the checksum; otherwise, a default value of 0 is used. #!/usr/bin/env python3 # -*- coding: utf-8 -*- # Import module import zlib s = b'Python' # using zlib.crc32() method t = zlib.crc32(s) print(t) # lower print(zlib.crc32(b'python')) 2742599054 2765404344 Changed in version 3.0: The result is always unsigned. CRC-32 algorithm This is a practical algorithm for the CRC-32 variant of CRC. Function CRC32 Input: data: Bytes // Array of bytes Output: crc32: UInt32 // 32-bit unsigned CRC-32 value // Initialize CRC-32 to starting value crc32 ← 0xFFFFFFFF for each byte in data do nLookupIndex ← (crc32 xor byte) and 0xFF; crc32 ← (crc32 shr 8) xor CRCTable[nLookupIndex] // CRCTable is an array of 256 32-bit constants // Finalize the CRC-32 value by inverting all the bits crc32 ← crc32 xor 0xFFFFFFFF return crc32
pooriabt

How to use hash function in Python

Secure hashes and message digests. Hash algorithms The hashlib module implements a common interface to many different secure hash and message digest algorithms. Included are the FIPS secure hash algorithms SHA1, SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA’s MD5 algorithm. #!/usr/bin/env python3 # Import module import hashlib m = hashlib.sha256() m.update(b"Sony Invests $1 Billion") b = m.digest() print(b) # a string object # b = m.hexdigest() print(f'digest_size:{m.digest_size}') print(f'block_size: {m.block_size}') b'W\xe2\xcab\xf7\xd7|\xe4\xe5%\x05R\xef\xa9\xb7F@,\xc1\xb0d\xbcN5/\xd0r4\x02x\x18\xb2' digest_size:32 block_size: 64 The named constructors are much faster than new() and should be preferred. A set containing the names of the hash algorithms that are available in the running Python interpreter. #!/usr/bin/env python3 # Import module import hashlib m = hashlib.algorithms_available for name in m: print(name) blake2b sha shake_256 ecdsa-with-SHA1 md4 sha1 dsaWithSHA sha224 sha3_384 sha3_256 sha384 md5 sha3_224 ripemd160 sha512 sha3_512 whirlpool shake_128 sha256 dsaEncryption blake2s Cryptographic hash Function BLAKE2 is a cryptographic hash function faster than MD5, SHA-1, SHA-2, and SHA-3, yet is at least as secure as the latest standard SHA-3. BLAKE2 has been adopted by many projects due to its high speed, security, and simplicity. BLAKE2b, optimized for 64-bit platforms and produces digests of any size between 1 and 64 bytes. BLAKE2s, optimized for 8- to 32-bit platforms and produces digests of any size between 1 and 32 bytes. #!/usr/bin/env python3 # Import module from hashlib import blake2b h = blake2b() h.update(b'123456') s = h.hexdigest() print(s) b3910b0f4b6f1aede44da90bb7705a868b265861b36e6f7f29dba7223f6f1ce7b10e0dd25e47deb70bd7f3b24f7da653409cd9014f8715e4013c15fee38ab418 BLAKE2 supports keyed mode (a faster and simpler replacement for HMAC), salted hashing, personalization, and tree hashing. Examples Using different digest sizes produce 20-byte digests: #!/usr/bin/env python3 # Import module from hashlib import blake2b h = blake2b(digest_size=20) h.update(b'123456') s = h.hexdigest() print(s) a0f92ddfdea4892ff18a48f7e0f9fcffc55745f5 Keyed hashing Keyed hashing can be used for authentication as a faster and simpler replacement for Hash-based message authentication code (HMAC). #!/usr/bin/env python3 # Import module from hashlib import blake2b h = blake2b(key=b'pseudorandom', digest_size=20) h.update(b'123456') s = h.hexdigest() print(s) 3ee7c11a5b81e04e30cbcbf87aa0179a35289b5d Randomized hashing In BLAKE2 the salt is processed as a one-time input to the hash function during initialization, rather than as an input to each compression function. #!/usr/bin/env python3 # Import module import os from hashlib import blake2b salt = os.urandom(blake2b.SALT_SIZE) h = blake2b(salt=salt) h.update(b'123456') s = h.hexdigest() print(s) 660d796feb633b636b1e0110a22b073227775cd10895dac25dd5a8a93b624869ec79774a0707db1635f2d297f55c7973500c6c22cf3982e11a74af09208befae bb644b1d0970050c40ddb5c8047f46269c369e5deea50c0ba53e49172722d14e6264f14d29085a00203947739a870dfc6d4c4eb0395f59c23f9faee314b344e7 Q: So I shouldn't use BLAKE2 for hashing user passwords? A: You shouldn't use *any* general-purpose hash function for user passwords, not BLAKE2, and not MD5, SHA-1, SHA-256, or SHA-3. Instead you should use a password hashing function such as the PHC winner Argon2 with appropriate time and memory cost parameters, to mitigate the risk of bruteforce attacks—Argon2's core uses a variant of BLAKE2's permutation.
Unused

How to fetch data from url in Python

Fetch Internet Resources Using The urllib Package. Fetching URLs The simplest way to use urllib.request is as follows: #!/usr/bin/env python3 # Import datetime module import urllib.request with urllib.request.urlopen('https://google.com') as response: html = response.read() # the same Request req = urllib.request.Request('https://google.com') with urllib.request.urlopen(req) as response: content = response.read() POST Data The data needs to be encoded in a standard way, and then passed to the Request object as the data argument. #!/usr/bin/env python3 # Import module import urllib.parse import urllib.request # POST url = 'https://google.com' param = {'q': 'Python'} data = urllib.parse.urlencode(param) # data should be bytes data = data.encode('ascii') req = urllib.request.Request(url, data) with urllib.request.urlopen(req) as response: content = response.read() # HTTP GET request url = 'https://google.com' param = {'q': 'Python'} data = urllib.parse.urlencode(param) print(data) full_url = url + '?' + data req = urllib.request.Request(url) with urllib.request.urlopen(req) as response: content = response.read() q=Python Headers By default urllib identifies itself as Python-urllib/x.y. #!/usr/bin/env python3 # Import module import urllib.parse import urllib.request # Headers url = 'https://installmd.com' param = {'q': 'Python'} headers = {'User-Agent': 'Mozilla/5.0'} data = urllib.parse.urlencode(param) # data should be bytes data = data.encode('ascii') req = urllib.request.Request(url, data, headers) with urllib.request.urlopen(req) as response: content = response.read() Handling Exceptions urlopen raises URLError when it cannot handle a response. #!/usr/bin/env python3 # Import module import urllib.error import urllib.request # no host given req = urllib.request.Request('https:/google.com') try: with urllib.request.urlopen(req) as response: content = response.read() except urllib.error.URLError as e: print(e.reason) no host given Error Codes # Table mapping response codes to messages; entries have the # form {code: (shortmessage, longmessage)}. responses = { 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), 200: ('OK', 'Request fulfilled, document follows'), 201: ('Created', 'Document created, URL follows'), 202: ('Accepted', 'Request accepted, processing continues off-line'), 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 204: ('No Content', 'Request fulfilled, nothing follows'), 205: ('Reset Content', 'Clear input form for further input.'), 206: ('Partial Content', 'Partial content follows.'), 300: ('Multiple Choices', 'Object has several resources -- see URI list'), 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 302: ('Found', 'Object moved temporarily -- see URI list'), 303: ('See Other', 'Object moved -- see Method and URL list'), 304: ('Not Modified', 'Document has not changed since given time'), 305: ('Use Proxy', 'You must use proxy specified in Location to access this ' 'resource.'), 307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), 400: ('Bad Request', 'Bad request syntax or unsupported method'), 401: ('Unauthorized', 'No permission -- see authorization schemes'), 402: ('Payment Required', 'No payment -- see charging schemes'), 403: ('Forbidden', 'Request forbidden -- authorization will not help'), 404: ('Not Found', 'Nothing matches the given URI'), 405: ('Method Not Allowed', 'Specified method is invalid for this server.'), 406: ('Not Acceptable', 'URI not available in preferred format.'), 407: ('Proxy Authentication Required', 'You must authenticate with ' 'this proxy before proceeding.'), 408: ('Request Timeout', 'Request timed out; try again later.'), 409: ('Conflict', 'Request conflict.'), 410: ('Gone', 'URI no longer exists and has been permanently removed.'), 411: ('Length Required', 'Client must specify Content-Length.'), 412: ('Precondition Failed', 'Precondition in headers is false.'), 413: ('Request Entity Too Large', 'Entity is too large.'), 414: ('Request-URI Too Long', 'URI is too long.'), 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'), 417: ('Expectation Failed', 'Expect condition could not be satisfied.'), 500: ('Internal Server Error', 'Server got itself in trouble'), 501: ('Not Implemented', 'Server does not support this operation'), 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 503: ('Service Unavailable', 'The server cannot process the request due to a high load'), 504: ('Gateway Timeout', 'The gateway server did not receive a timely response'), 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'), }
pooriabt

How to format a string in Python

Python String Formatting Best Practices. Fancier Output Formatting To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark. Inside this string, you can write a Python expression between { and } characters that can refer to variables or literal values. #!/usr/bin/env python3 # Import math module import math print(f'The value of pi is approximately {math.pi:5.3f}') weather = {"Tue":78, "Wed": 60, "Thu": 60} for name, data in weather.items(): print(f'{name:3} => {data:2d}') The value of pi is approximately 3.142 Tue => 78 Wed => 60 Thu => 60 The String format() Method Basic usage of the str.format() method looks like this: #!/usr/bin/env python3 # Import math module import math print('The value of pi is approximately {:07.3f}'.format(math.pi)) print('{1} and {0}'.format('spam', 'eggs')) The value of pi is approximately 003.142 eggs and spam Using type-specific formatting: #!/usr/bin/env python3 # Import datetime module from datetime import datetime curr = datetime.now() print('{:%Y-%m-%d %H:%M:%S}'.format(curr)) # 2022-04-11 12:01:54 # Using the comma as a thousands separator: print('{:,}'.format(1234567890)) # 1,234,567,890 2022-04-11 12:01:54 1,234,567,890 Old String Formatting with % Operator The % operator (modulo) can also be used for string formatting. Given 'string' % values, instances of % in string are replaced with zero or more elements of values. This operation is commonly known as string interpolation. For example: #!/usr/bin/env python3 # Import math module import math print('PI :: %5.3f' % math.pi) # padded print('PI :: %007.3f' % math.pi) PI :: 3.142 PI :: 003.142 The conversion flag characters are: flag characters: ##### '#' The value conversion will use the “alternate form” (where defined below). ##### '0' The conversion will be zero padded for numeric values. ##### '-' The converted value is left adjusted (overrides the '0' conversion if both are given). ##### ' ' (a space) A blank should be left before a positive number (or empty string) produced by a signed conversion. ##### '+' A sign character ('+' or '-') will precede the conversion (overrides a “space” flag). A length modifier (h, l, or L) may be present, but is ignored as it is not necessary for Python – so e.g. %ld is identical to %d. The conversion types are: types: ##### 'd' Signed integer decimal. ##### 'i' Signed integer decimal. ##### 'o' Signed octal value. ##### 'u' Obsolete type – it is identical to 'd'. ##### 'x' Signed hexadecimal (lowercase). ##### 'X' Signed hexadecimal (uppercase). ##### 'e' Floating point exponential format (lowercase). ##### 'E' Floating point exponential format (uppercase). ##### 'f' Floating point decimal format. ##### 'F' Floating point decimal format. ##### 'g' Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. ##### 'G' Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. ##### 'c' Single character (accepts integer or single character string). ##### 'r' String (converts any Python object using repr()). ##### 's' String (converts any Python object using str()). ##### 'a' String (converts any Python object using ascii()). ##### '%' No argument is converted, results in a '%' character in the result.
Sambhav Khandelwal

How to use string constants in Python

String Constants Best Practice. String Constants in Python The constants defined in this module are: String constants: ##### string.ascii_letters The concatenation of the ascii_lowercase and ascii_uppercase constants described below. This value is not locale-dependent. ##### string.ascii_lowercase The lowercase letters 'abcdefghijklmnopqrstuvwxyz'. This value is not locale-dependent and will not change. ##### string.ascii_uppercase The uppercase letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. This value is not locale-dependent and will not change. ##### string.digits The string '0123456789'. ##### string.hexdigits The string '0123456789abcdefABCDEF'. ##### string.octdigits The string '01234567'. ##### string.punctuation String of ASCII characters which are considered punctuation characters in the C locale: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~. ##### string.printable String of ASCII characters which are considered printable. This is a combination of digits, ascii_letters, punctuation, and whitespace. ##### string.whitespace A string containing all ASCII characters that are considered whitespace. This includes the characters space, tab, linefeed, return, formfeed, and vertical tab. Use of ascii_lowercase Constant #!/usr/bin/env python3 import string if 'a' in string.ascii_lowercase: print("Found!") print(string.ascii_lowercase) Found! abcdefghijklmnopqrstuvwxyz Use of string.digits Constant #!/usr/bin/env python3 import string for a in string.digits: print(a) 0 1 2 3 4 5 6 7 8 9
Tomoki

How to convert string to json in Python

Converting Json to string in Python. Decoding JSON To convert string to json in Python, use the json.loads() function. The json.loads() is a built-in Python function that accepts a valid json string and returns a dictionary to access all elements. The json.loads() function is used to parse valid JSON string into dictionary. import json s = '''{ "name":"Android", "version":13 }''' d = json.loads(s) print(d) print(json.loads('"\\"foo\\bar"')) {u'version': 13, u'name': u'Android'} "foar Encoding JSON To convert string to json in Python, use the json.dumps() function. import json s = json.dumps(['foo', {'bar': ('baz', None, 0.1, 2)}]) print(s) ["foo", {"bar": ["baz", null, 0.1, 2]}] Translations Performs the following translations in decoding by default: object dict array list string str number (int) int number (real) float true True false False null None Using json.tool Command Line Interface Using json.tool from the shell to validate and pretty-print: Python pretty echo '{"json":"obj"}' | python -m json.tool { "json": "obj" } json.tool Options The json.tool module provides a simple command line interface to validate and pretty-print JSON objects. Command line options:infileThe JSON file to be validated or pretty-printed.outfileWrite the output of the infile to the given outfile. Otherwise, write it to sys.stdout.--sort-keysSort the output of dictionaries alphabetically by key.--no-ensure-asciiDisable escaping of non-ascii characters, see json.dumps() for more information.--json-linesParse every input line as separate JSON object.--indent, --tab, --no-indent, --compactMutually exclusive options for whitespace control.-h, --helpShow the help message.
pooriabt

How to check if string contains substring in Python

Does Python have a string 'contains' substring method?. Using the in Operator The easiest way to check if a Python string contains a substring is to use the in operator. str = "Python" if "th" in str: print("Found!") # case-insensitive if "TH" not in str: print("Not found!") Found! Not found! Using str.Index Method If the substring is not found, a ValueError exception is thrown, which can be handled with a try-except-else block: str = "Python" try: i = str.index("th") print(i) #Found! except ValueError: print("Not found!") Using str.find Method Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found. str = "Python" # str.find(sub[, start[, end]]) if str.find("th") != -1: print("Found!") Found! The find() method should be used only if you need to know the position of sub. To check if sub is a substring or not, use the in operator:
Patcher56

How to check if key exists in a dictionary in Python

Check if a given key already exists in a dictionary. Using the in operator In this method, we use the membership operator in. This operator is used to check if one value is a member of another. It returns a boolean value. dict = {"GMT": 0, "BST": 1} if "GMT" in dict: print("Exists") # not in if "gmt" not in dict: print("Does not exist") Exists Does not exist However, remember the in operator is case sensitive hence you could either ensure all your keys are in the same case or you could use the upper() or lower() methods respectively. Using the get Method Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError. dict = {"GMT": 0, "BST": 1} if dict.get("GMT") is not None: print("Exists") if dict.get("gmt") is None: print("Does not exist") Exists Does not exist Using EAFP EAFP or ‘Easier to Ask for Forgiveness than Permission’ means holding an optimistic view for the code you are working on, and if an exception is thrown catch it and deal with it later. dict = {"GMT": 0, "BST": 1} try: v = dict["GMT"] # key exists in dict except KeyError: # key doesn't exist in dict
Patcher56

Built-in Types in Python

Python’s Core Data Types. Core Data Types The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Built-in objects preview: Object type: ##### Numbers int, float, complex. ##### Strings 'spam', "Bob's", b'a\x01c', u'sp\xc4m' ##### Lists [1, [2, 'three'], 4.5],list(range(10)) ##### Dictionaries {'food': 'spam', 'taste': 'yum'},dict(hours=10) ##### Tuples (1, 'spam', 4, 'U'),tuple('spam'),namedtuple ##### Files open('eggs.json') ##### Sets set('abc'),{'a', 'b', 'c'} ##### Other core types Booleans, types, None ##### Program unit types Functions, modules, classes ##### Implementation-related types Compiled code, stack tracebacks Numeric Types There are three distinct numeric types: integers, floating point numbers, and complex numbers. # Built-in Types # Numeric Types import math # Integer addition print(123+345) # 2 to the power 100, again print(2**100) # math module print(math.pi) 468 1267650600228229401496703205376 3.141592653589793 Sequence Types There are three basic sequence types: lists, tuples, and range objects. # Built-in Types # Sequence Types # in operations print("yt" in "byte") # lists lists = [[]] * 3 lists = [[] for i in range(3)] print(lists) True [[], [], []] Mapping Types A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. # Built-in Types # Mapping Types d = dict(a=1, b=2, c=3) e = {'a':1, 'b':2}
Unused

Hello World in Python

Hello, World! is the first basic program in any programming language.Python Version Print the Python version number and exit. Example output could be: Python version python -V python --version Python 3.9.1 Running Files with Command Lines You can ask Python to run it by listing its full filename as the first argument to a python command like the following typed at the system shell prompt. run python hellowrold.py hello,世界 Type the following statements into a new text file named hellowrold.py: # A first Python script # hellowrold.py print('hello,世界') The Interactive Prompt Assuming the interpreter is installed as an executable program on your system, the most platform- neutral way to start an interactive interpreter session is usually just to type python at your operating system’s prompt, without any arguments. For example: session python Python 3.9.1 (default, Oct 15 2021, 22:19:38) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> On Windows, a Ctrl-Z gets you out of this session; on Unix, try Ctrl-D instead.
ada

How to find the difference between two slices in Go

Comparing two slices in Go. Using map cache Creates a slice of slice values not included in the other given slices. An implementation is shown in the section below. package main import "fmt" // difference returns the elements in `a` that aren't in `b`. func difference(a, b []string) ([]string, error) { // uses empty struct (0 bytes) for map values. m := make(map[string]struct{}, len(b)) // cached for _, v := range b { m[v] = struct{}{} } var diff []string for _, v := range a { if _, ok := m[v]; !ok { diff = append(diff, v) } } return diff, nil } func main() { s1 := []string{"a", "b"} s2 := []string{"b", "c", "d"} // find s1 strings not in s2 s, _ := difference(s1, s2) fmt.Println(s) // find s2 strings not in s1 s, _ = difference(s2, s1) fmt.Println(s) } [a] [c d] You can use reflect.TypeOf for any []T. Using simple loops Comparing two slices for missing element. For example, package main import "fmt" func difference(a, b []string) ([]string, error) { var diff []string for _, m := range a { ok := false for _, n := range b { if m == n { ok = true break } } if !ok { diff = append(diff, m) } } return diff, nil } func main() { s1 := []string{"a", "b"} s2 := []string{"b", "c", "d"} // find s1 strings not in s2 s, _ := difference(s1, s2) fmt.Println(s) // find s2 strings not in s1 s, _ = difference(s2, s1) fmt.Println(s) } [a] [c d] Returns the new slice of filtered values.
aweis

How to split a slice into equally sized chunks in Go

Slice chunking in Go. Using for Loop The easiest method involves iterating over the slice and incrementing by the chunk size. An implementation is shown in the section below. package main import "fmt" func chunkSlice(slice []int, chunkSize int) ([][]int, error) { chunks := make([][]int, 0, (len(slice)+chunkSize-1)/chunkSize) for chunkSize < len(slice) { slice, chunks = slice[chunkSize:], append(chunks, slice[0:chunkSize:chunkSize]) } chunks = append(chunks, slice) return chunks, nil } func main() { slice := []int{1, 2, 3, 4, 5, 6, 7} chunks, _ := chunkSlice(slice, 3) fmt.Println(chunks) } [[1 2 3] [4 5 6] [7]] You can use reflect.TypeOf for any []T. Another variant A general solution to split a slice to into sub-slices of equal length. package main import "fmt" func chunkSlice(slice []int, chunkSize int) ([][]int, error) { chunks := make([][]int, 0, (len(slice)+chunkSize-1)/chunkSize) var j int for i := 0; i < len(slice); i += chunkSize { j += chunkSize if j > len(slice) { j = len(slice) } chunks = append(chunks, slice[i:j]) } return chunks, nil } func main() { slice := []int{1, 2, 3, 4, 5, 6, 7} chunks, _ := chunkSlice(slice, 3) fmt.Println(chunks) } [[1 2 3] [4 5 6] [7]] Note that if the slice length is not divisible by the chunk size, the last chunk will be less than the chunk size.
Unused

How to use range in Go

Range loop (for-each) patterns. For-each Loop (slice or map) The range form of the for loop iterates over a slice or map. When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index. package main import "fmt" func main() { var pow = []int{1, 2, 4, 8, 16, 32} for i, v := range pow { fmt.Printf("%d = %d\n", i, v) } } 0 = 1 1 = 2 2 = 4 3 = 8 4 = 16 5 = 32 Iterating over a string For strings, the range loop iterates over Unicode code points. package main import "fmt" func main() { for i, ch := range "abc言語" { fmt.Printf("%#U position %d\n", ch, i) } } U+0061 'a' position 0 U+0062 'b' position 1 U+0063 'c' position 2 U+8A00 '言' position 3 U+8A9E '語' position 6 Iterating over a map The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next. package main import "fmt" func main() { m := map[string]int64{ "UTC": 0 * 60 * 60, "BST": 1 * 60 * 60, "CST": -6 * 60 * 60, } for i, v := range m { fmt.Printf("%s => %d\n", i, v) } } UTC => 0 BST => 3600 CST => -21600 Iterating over channels For channels, the iteration values are the successive values sent on the channel until its close. package main import "fmt" func main() { ch := make(chan int) go func() { ch <- 1 ch <- 3 ch <- 5 close(ch) }() for n := range ch { fmt.Println(n) } } 1 3 5 Iterate over a range of integers If you want to just iterate over a range w/o using and indices or anything else. No extra declaration needed, no _. package main func main() { for range [5]int{} { // Body... } }
Unused