Home > Backend Development > Golang > How to Replicate Python's `ord()` and `chr()` in Go?

How to Replicate Python's `ord()` and `chr()` in Go?

Susan Sarandon
Release: 2024-12-11 17:27:11
Original
630 people have browsed it

How to Replicate Python's `ord()` and `chr()` in Go?

Translating Python's ord() and chr() Functionality to Go

Python provides two essential functions, ord() and chr(), for converting characters to their respective Unicode code points and vice versa. In Go, these conversions can be achieved through straightforward type conversions.

ord() Equivalent

To obtain the Unicode code point of a character in Go, you can simply convert the character to a rune data type. The following code illustrates this:

ch := rune(97)
Copy after login

The result stored in the ch variable will be 97, indicating the Unicode code point for the character 'a'.

chr() Equivalent

To convert a Unicode code point to its corresponding character, you can cast the code point to a rune and assign it to a string variable. For example:

n := int('a')
Copy after login

In this case, the n variable will contain the value 97, representing the Unicode code point for 'a'.

Additional Functionality

Go also provides a way to convert directly from an integer numeric value to a string, which interprets the value as a UTF-8 encoded character. This can be achieved as follows:

s := string(97)
Copy after login

In this example, the s variable will contain the string "a", representing the character associated with the Unicode code point 97.

Note

Unlike in Python, where the chr() function can take an integer and return a character, Go uses the rune data type to represent Unicode characters internally. Runes are 32-bit integers that represent Unicode code points, allowing for the representation of a wide range of characters.

The above is the detailed content of How to Replicate Python's `ord()` and `chr()` in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template