Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2c82742

Browse files
committed
Handle flags, width and precision implemented (string formatting)
1 parent d178ce8 commit 2c82742

File tree

2 files changed

+44
-3
lines changed

2 files changed

+44
-3
lines changed

java2python/mod/transform.py

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -106,11 +106,33 @@ def formatSyntaxTransf(match):
106106
return '\\n' # Py converts \n to os.linesep
107107

108108
result = '{'
109-
# TODO: add flags, width and precision
109+
thous_sep = ''
110+
110111
if(groups['idx']):
111112
idx = int(groups['idx'][:-1])
112113
result += str(idx - 1) # Py starts count from 0
113-
result += ':' + groups['convers'] + '}'
114+
result += ':'
115+
116+
if(groups['flags']):
117+
if ',' in groups['flags']:
118+
thous_sep = ','
119+
if '+' in groups['flags']:
120+
result += '+'
121+
elif ' ' in groups['flags']:
122+
result += ' '
123+
if '#' in groups['flags']:
124+
result += '#'
125+
if '0' in groups['flags']:
126+
result += '0'
127+
128+
if(groups['width']):
129+
result += groups['width']
130+
result += thous_sep
131+
132+
if(groups['precision']):
133+
result += groups['precision']
134+
135+
result += groups['convers'] + '}'
114136

115137
return result
116138

@@ -128,7 +150,7 @@ def formatString(node, config):
128150
format = call_args[0].firstChildOfType(tokens.STRING_LITERAL)
129151
if format:
130152
format.token.text = \
131-
re.sub(r'%(?P<idx>\d+\$)?(?P<convers>[scdoxefgn])',
153+
re.sub(r'%(?P<idx>\d+\$)?(?P<flags>[-+# 0,]+)?(?P<width>[0-9]+)?(?P<precision>\.[0-9]+)?(?P<convers>[scdoxefgn])',
132154
formatSyntaxTransf,
133155
format.token.text,
134156
flags=re.IGNORECASE)

test/Format1.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
public class Format1 {
2+
public static void main(String[] args) {
3+
long n = 461012;
4+
String f1 = String.format("%d%n", n); // --> "461012"
5+
String f2 = String.format("%08d%n", n); // --> "00461012"
6+
String f3 = String.format("%+8d%n", n); // --> " +461012"
7+
String f4 = String.format("%,8d%n", n); // --> " 461,012"
8+
String f5 = String.format("%+,8d%n", n); // --> "+461,012"
9+
10+
System.out.println(f1 + f2 + f3 + f4 + f5);
11+
12+
double pi = 3.14159265;
13+
String pf1 = String.format("%f%n", pi); // --> "3.141593"
14+
String pf2 = String.format("%.3f%n", pi); // --> "3.142"
15+
String pf3 = String.format("%10.3f%n", pi); // --> " 3.142"
16+
17+
System.out.println(pf1 + pf2 + pf3);
18+
}
19+
}

0 commit comments

Comments
 (0)