How to extract a substring from a string using position and length

Hello,
Example:
string1 = ‘abcdefghijk’
I need to extract a substring from 4th position for a length of 2 characters
I tried this Python code and I get a syntax error:
substring1 = string1(3:2)
(the result in substring should be ‘de’ if it works)

Thanks for help.

1 Like

try this

String s = (String1[3:4]); // Returns “de”

1 Like

Thanks, it works with [3:5] (as [3:4] returns only ‘d’).

1 Like
pos4th = 4 - 1     # 3
len2 = pos4th + 2  # 5

abc = 'abcdefghijk'
de = abc[pos4th:len2]

print abc, de, ENTER, pos4th, len2
exit()
4 Likes

Substring function in python extract sub strings with the sense of StartIndex , EndIndex-1

2 Likes

Indeed, left side value of : is inclusive; while right side value is exclusive. :nerd_face:

4 Likes

Found more ‘slice’ options for future use :slightly_smiling_face:
https://py.processing.org/reference/slice.html

2 Likes