Nathan Nathan - 1 year ago 132
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
without using brackets (

Answer Source

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
# "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)
# "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)
# "4"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download