Skip to content

Commit

Permalink
Add str.zfill()
Browse files Browse the repository at this point in the history
  • Loading branch information
SanketDG committed Feb 16, 2018
1 parent cdbf3ff commit a913dfe
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 1 deletion.
41 changes: 40 additions & 1 deletion python/common/org/python/types/Str.java
Original file line number Diff line number Diff line change
Expand Up @@ -1764,8 +1764,47 @@ public org.python.Object translate() {
public org.python.Object upper() {
return new org.python.types.Str(this.value.toUpperCase());
}
}

@org.python.Method(
__doc__ = "S.zfill() -> str\n" +
"\n" +
"Return a copy of the string left filled with ASCII '0' \n" +
"digits to make a string of length width.\n",
args = {"width"}
)
public org.python.Object zfill(org.python.Object width) {


if (width instanceof org.python.types.Float) {
throw new org.python.exceptions.TypeError("integer argument expected, got float");
}
else if (!(width instanceof org.python.types.Int)) {
throw new org.python.exceptions.TypeError("'" + org.Python.typeName(width.getClass()) +
"' object cannot be interpreted as an integer");
}

int w = (int) ((org.python.types.Int) width).value;

if (this.value.length() >= w) {
return new org.python.types.Str(this.value);
}

int fill = w - this.value.length();

java.lang.StringBuffer str = new java.lang.StringBuffer(w);

if (this.value.length() != 0 && (this.value.charAt(0) == '-' || this.value.charAt(0) == '+')) {
str.append(this.value.charAt(0));
this.value = this.value.substring(1);
}

for(int i = 0; i < fill; i++) {
str.append('0');
}

return new org.python.types.Str(str.toString() + this.value);
}
}

final class PythonFormatter {

Expand Down
34 changes: 34 additions & 0 deletions tests/datatypes/test_str.py
Original file line number Diff line number Diff line change
Expand Up @@ -778,6 +778,40 @@ def test_splitlines(self):
print(s1.splitlines(True))
""")

def test_zfill(self):
self.assertCodeExecution("""
s = '42'
print(s.zfill(5))
try:
print(s.zfill('string'))
except TypeError as err:
print(err)
try:
print(s.zfill({}))
except TypeError as err:
print(err)
s = '-42'
print(s.zfill(5))
s = '+42'
print(s.zfill(5))
s = ''
print(s.zfill(5))
s = '-.-42'
print(s.zfill(6))
""")

@expectedFailure
def test_zfill_arg_handling():
self.assertCodeExecution("""
s = "42"
s.zfill()
""")

class UnaryStrOperationTests(UnaryOperationTestCase, TranspileTestCase):
data_type = 'str'
Expand Down

0 comments on commit a913dfe

Please sign in to comment.