0

I found this code at Stack Overflow:

input_filename = "to_modify.xlsx"
wb = load_workbook(input_filename)
# Get first sheet
sh: worksheet = wb[wb.sheetnames[0]]

The link is here: How to change font size in Python OpenPyXL

So, I tried in a simplified way as:

str = [1, 2, 3, 4]
bo: fo = str[str[0]]

And it gave me the error message: TypeError: 'type' object is not subscriptable

What is the idea here? Why I need this : character?

Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
  • Have you tried it without using `str` as the variable name? That represents the string type, so it might think you are trying to do an index on a type value – TheDude Apr 07 '21 at 17:23

1 Answers1

0

A couple of things are going on here.

In this context the : indicates type hinting.

sh: worksheet = wb[wb.sheetnames[0]]

means that 'sh' refers to a 'worksheet' and is initialized to the first workbook of 'wb'

You aren't obliged to use type hinting at all, but it's a good idea for larger collaborative projects; if nothing else it helps readability.

For your own example, you made an unlucky choice of 'str' because that's reserved as a type in python. Here are some possible alternatives that hopefully make sense to you:

s: str = 'abcd' # s is of type 'str' and set to 'abcd'
fibos: list = [1, 2, 3, 5, 8, 13, 21, 34] # fibos is a list
s, fibos
#('abcd', [1, 2, 3, 5, 8, 13, 21, 34])
Jamie Deith
  • 706
  • 2
  • 4