Java-Python string manipulation contrast
This is a comparison of basic character operations between Java 8 and Python 3.
String match
| Java |
Python |
result |
| "abc".equals("abc") |
'abc' == 'abc' |
True |
String length
| Java |
Python |
result |
| "abcde".length() |
len('abcde') |
5 |
Part of the string
| Java |
Python |
result |
| "abcde".substring(1) |
'abcde'[1:] |
'bcde' |
| "abcde".substring(0,2) |
"abcde"[:2] |
'ab' |
| "abcde".substring(1,4) |
'abcde'[1:4] |
'bcd' |
| "abcde".substring(0,"abcde".length()-2) |
'abcde'[:-2] |
'abc' |
First position of the specified character
| Java |
Python |
result |
| "abcde".indexOf('d') |
'abcde'.find('d') |
3 |
| "abcde".indexOf('X') |
'abcde'.find('X') |
-1 |
Does the string start with the specified prefix?
| Java |
Python |
result |
| "abcde".startsWith("abc") |
'abcde'.startswith('abc') |
True |
| "abcde".startsWith("bcd") |
'abcde'.startswith('bcd') |
False |
Does the string end with the specified suffix?
| Java |
Python |
result |
| "abcde".endsWith("de") |
'abcde'.endswith('de') |
True |
| "abcde".endsWith("cd") |
'abcde'.endswith('cd') |
False |
Does the string contain the specified string?
| Java |
Python |
result |
| "abcde".contains("bcd") |
"bcd" in "abcde" |
True |
| "abcde".contains("ae") |
"ae" in "abcde" |
False |
String to number
| Java |
Python |
result |
| Integer.parseInt("1")+2 |
int('1')+2 |
3 |
Numeric to string
| Java |
Python |
result |
| String.valueOf(1)+"2" |
str(1)+'2' |
'12' |
| String.valueOf(1)+2 |
str(1)+2 |
Error in python |
Splitting strings
| Java |
Python |
result |
| "a,b,c".split(",") |
'a,b,c'.split(',') |
['a', 'b', 'c'] |
String concatenation
| Java |
Python |
result |
| String.join(",", new String[]{"a","b","c"}) |
",".join(['a', 'b', 'c']) |
'a,b,c' |
import org.apache.commons.lang3.StringUtils;
StringUtils.join(new String[]{"a","b","c"},",")
Document link
Check here for the rest
Java8 Class String
Python2 system "3.6.1 string method"
Python3 series "4.7. Text sequence type"
Revision history
2016/3/14 First edition
2016/3/15 Added equals, startsWith, endsWith, contains