Nathan Nathan - 4 months ago 20
Python Question

Slicing a string in Python without brackets

Let's say I have a string like

num = "12345"
; how do I print it as one character like
1
or
2
without using brackets (
print(num[0])
)?

Answer

The brackets are probably the correct way to do this, why do not want you to use it?

Anyway, you can unpack your string (only work with Python 3 as @DeepSpace precised), like this:

letter, *_ = num
print(letter)
# "1"

It works also for multiple variables anywhere:

letter_1, *_, letter_2 = num
print(letter_1, letter_2)
# "1", "5"

There is also operator.getitem(a, b), which behaves like the brackets but as a function:

from operator import getitem

letter = getitem(num, 0)
print(letter)
# "1"

Finally, as @EliKorvigo pointed it out, there is operator.itemgetter(item) which creates a function acting just like the brackets:

from operator import itemgetter

getter = itemgetter(3)
letter = getter(num)
print(letter)
# "4"