Skip to content

Commit b61b454

Browse files
committed
builtin: Implement builtin_ascii
Implement builtin ascii
1 parent c5b8c68 commit b61b454

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

‎builtin/builtin.go‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
package builtin
77

88
import (
9+
"strconv"
10+
"strings"
11+
"unicode"
912
"unicode/utf8"
1013

1114
"github.com/go-python/gpython/compile"
@@ -24,7 +27,7 @@ func init(){
2427
py.MustNewMethod("abs", builtin_abs, 0, abs_doc),
2528
py.MustNewMethod("all", builtin_all, 0, all_doc),
2629
py.MustNewMethod("any", builtin_any, 0, any_doc),
27-
// py.MustNewMethod("ascii", builtin_ascii, 0, ascii_doc),
30+
py.MustNewMethod("ascii", builtin_ascii, 0, ascii_doc),
2831
// py.MustNewMethod("bin", builtin_bin, 0, bin_doc),
2932
// py.MustNewMethod("callable", builtin_callable, 0, callable_doc),
3033
py.MustNewMethod("chr", builtin_chr, 0, chr_doc),
@@ -309,6 +312,36 @@ func builtin_any(self, seq py.Object) (py.Object, error){
309312
returnpy.False, nil
310313
}
311314

315+
constascii_doc=`ascii(obj, /)
316+
Return an ASCII-only representation of an object.
317+
318+
As repr(), return a string containing a printable representation of an
319+
object, but escape the non-ASCII characters in the string returned by
320+
repr() using \\x, \\u or \\U escapes. This generates a string similar
321+
to that returned by repr() in Python 2
322+
`
323+
324+
funcbuiltin_ascii(self, o py.Object) (py.Object, error){
325+
reprObject, err:=py.Repr(o)
326+
iferr!=nil{
327+
returnnil, err
328+
}
329+
330+
varsb strings.Builder
331+
repr:=reprObject.(py.String)
332+
for_, c:=rangerepr{
333+
ifc<=unicode.MaxASCII{
334+
sb.WriteRune(c)
335+
} else{
336+
s:="\\u"+strconv.FormatInt(int64(c), 16)
337+
sb.WriteString(s)
338+
}
339+
}
340+
341+
ascii:=sb.String()
342+
returnpy.String(ascii), nil
343+
}
344+
312345
constround_doc=`round(number[, ndigits]) -> number
313346
314347
Round a number to a given precision in decimal digits (default 0 digits).

‎builtin/tests/builtin.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@
1919
assertany(["hello", "world"]) ==True
2020
assertany([]) ==False
2121

22+
doc="ascii"
23+
assertascii('hello world') =="'hello world'"
24+
assertascii('안녕 세상') =="'\\uc548\\ub155 \\uc138\\uc0c1'"
25+
2226
doc="chr"
2327
assertchr(65) =="A"
2428
assertchr(163) =="£"

0 commit comments

Comments
(0)