-1

If I have a string of variable length and I want to return only first 3 characters of the string.

str[:3]

this works but I want to know if the string is of lesser length, suppose 2, "ab" or just "a", will this slicing work for that too? Thanks in advance

  • 4
    Welcome to Stack overflow! You know, you can always fire up a python command line and test it for yourself... – ori6151 Oct 19 '19 at 22:16
  • 1
    @ori6151 some of us are just Python theorists on here! – Huw Thomas Oct 19 '19 at 22:16
  • 1
    See the documentation and existing references for such trivial questions: “python slice string” or “python slice documentation” on google return relevant results. The following appears in the results - https://stackoverflow.com/questions/509211/understanding-slice-notation – user2864740 Oct 19 '19 at 22:18

2 Answers2

1

Python will return at most :n characters: 'a'[:3] will simply return 'a'. ''[:3] returns ''.

Pete
  • 421
  • 3
  • 6
1

You could have tested for yourself in less time than it would have taken to open your browser.

But yes.

Huw Thomas
  • 317
  • 1
  • 8