Skip to content

Commit

Permalink
Added str.ljust()
Browse files Browse the repository at this point in the history
  • Loading branch information
sohit-nayak committed Mar 4, 2017
1 parent 0c2509c commit deec6a9
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 4 deletions.
37 changes: 33 additions & 4 deletions python/common/org/python/types/Str.java
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
package org.python.types;
import org.Python;

import java.util.ArrayList;

Expand Down Expand Up @@ -831,10 +832,38 @@ public org.python.Object join(org.python.Object iterable) {
}

@org.python.Method(
__doc__ = ""
)
public org.python.Object ljust() {
throw new org.python.exceptions.NotImplementedError("ljust() has not been implemented.");
__doc__ = "S.ljust(width, fillChar=' ') -> str\nReturns the string left justified in a string of length width." +
"\nPadding is done using the specified fillchar (default is a space)." +
"\nThe original string is returned if width is less than len(s)",
args = {"width"},
default_args = {"fillChar"}
)
public org.python.Object ljust(org.python.Object width, org.python.Object fillChar) {
java.lang.String ch = new java.lang.String();
if (fillChar instanceof org.python.types.Str) {
if(((org.python.types.Str) fillChar).value.length() != 1) {
throw new org.python.exceptions.TypeError("The fill character must be exactly one character long");
}
ch = ((org.python.types.Str) fillChar).value;
} else if (fillChar == null) {
ch = " ";
} else {
throw new org.python.exceptions.TypeError("The fill character cannot be converted to Unicode");
}
if (width instanceof org.python.types.Int) {
int w = (int)((org.python.types.Int) width).value;
if (w < this.value.length()) {
return new org.python.types.Str(this.value);
}
java.lang.StringBuffer str = new java.lang.StringBuffer(w);
str.append(this.value);
int balance = w - this.value.length();
for (int i = 0; i < balance; i++) {
str.append(ch);
}
return new org.python.types.Str(str.toString());
}
return new org.python.exceptions.TypeError("integer argument expected, got " + Python.typeName(width.getClass()));
}

@org.python.Method(
Expand Down
20 changes: 20 additions & 0 deletions tests/datatypes/test_str.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,26 @@ def test_center(self):
except AttributeError as err:
print(err)
""")
def test_ljust(self):
self.assertCodeExecution("""
s = "abc"
print(s.ljust(5, "P"))
print(s.ljust(2))
print(s.ljust(15, "0"))
try:
print(s.ljust(16, 5.6))
except TypeError as err:
print(err)
try:
print(s.ljust(5.0, "P"))
except TypeError as err:
print(err)
s = 9
try:
print(s.ljust(8))
except AttributeError as err:
print(err)
""")


class UnaryStrOperationTests(UnaryOperationTestCase, TranspileTestCase):
Expand Down

0 comments on commit deec6a9

Please sign in to comment.