Skip to content

Commit db65820

Browse files
committed
Added str.zfill
1 parent 22ea159 commit db65820

File tree

3 files changed

+39
-3
lines changed

3 files changed

+39
-3
lines changed

src/lpython/semantics/python_ast_to_asr.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7598,6 +7598,25 @@ class BodyVisitor : public CommonVisitor<BodyVisitor> {
75987598
value.m_value = args[0].m_value;
75997599
fn_args.push_back(al, value);
76007600
}
7601+
} else if (attr_name == "zfill") {
7602+
if (args.size() != 1) {
7603+
throw SemanticError("str.zfill() takes one argument", loc);
7604+
}
7605+
ASR::expr_t *arg_sub = args[0].m_value;
7606+
ASR::ttype_t *arg_sub_type = ASRUtils::expr_type(arg_sub);
7607+
if (!ASRUtils::is_integer(*arg_sub_type)) {
7608+
throw SemanticError("str.zfill() argument must be integer", loc);
7609+
}
7610+
fn_call_name = "_lpython_str_zfill";
7611+
ASR::call_arg_t str;
7612+
str.loc = loc;
7613+
str.m_value = s_var;
7614+
7615+
ASR::call_arg_t width;
7616+
width.loc = loc;
7617+
width.m_value = args[0].m_value;
7618+
fn_args.push_back(al, str);
7619+
fn_args.push_back(al, width);
76017620
} else if(attr_name.size() > 2 && attr_name[0] == 'i' && attr_name[1] == 's') {
76027621
/*
76037622
String Validation Methods i.e all "is" based functions are handled here

src/lpython/semantics/python_comptime_eval.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,8 @@ struct PythonIntrinsicProcedures {
102102
{"_lpython_str_isascii", {m_builtin, &not_implemented}},
103103
{"_lpython_str_isspace", {m_builtin, &not_implemented}},
104104
{"_lpython_str_center", {m_builtin, &not_implemented}},
105-
{"_lpython_str_expandtabs", {m_builtin, &not_implemented}}
105+
{"_lpython_str_expandtabs", {m_builtin, &not_implemented}},
106+
{"_lpython_str_zfill", {m_builtin, &not_implemented}}
106107
};
107108
}
108109

src/runtime/lpython_builtin.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
from lpython import (i8, i16, i32, i64, f32, f64, c32, c64, overload, u8,
2-
u16, u32, u64)
1+
from lpython import (c32, c64, f32, f64, i8, i16, i32, i64, overload, u8, u16,
2+
u32, u64)
3+
34
#from sys import exit
45

56
#: abs() as a generic procedure.
@@ -1135,6 +1136,21 @@ def _lpython_str_expandtabs(s: str, tabsize: i32) -> str:
11351136
def _lpython_str_expandtabs(s: str) -> str:
11361137
return _lpython_str_expandtabs(s, 8)
11371138

1139+
def _lpython_str_zfill(s: str, width: i32) -> str:
1140+
print(width)
1141+
1142+
if (width <= len(s) ):
1143+
return s
1144+
ret: str
1145+
ret = "0"*(width-len(s))
1146+
1147+
if (s[0] == '+' or s[0] == '-'):
1148+
ret = s[0] + ret + s[1:]
1149+
else:
1150+
ret = ret + s
1151+
1152+
return ret
1153+
11381154
def list(s: str) -> list[str]:
11391155
l: list[str] = []
11401156
i: i32

0 commit comments

Comments
 (0)