0

I am new to python and a part of this course says this:

The following line of code will print the first character in each of the firstname and surname variables. Python starts counting at 0, so "Tom" would be T=0, o=1 and m=2.

print("Your initials are:",firstname[0],surname[0])

The question I am taking is where you have to take three letters from the start of a variable using this method, I am stuck so far, can anyone correct me.

surname = input () #input :smith
print (surname[0][1][2])
halfer
  • 19,824
  • 17
  • 99
  • 186
cameron claridge
  • 33
  • 1
  • 1
  • 3
  • 4
    I'd suggest you to google any basic python string/list tutorial or documentation. – Teemu Risikko Feb 23 '17 at 11:30
  • try print surname[:3] . Hope this helps! – Keerthana Prabhakaran Feb 23 '17 at 11:31
  • 1
    How do you suppose it should work? You have "Smith" in `surname`, so `surname[0]` is "S"; now you are trying to do `surname[0][1][2]`, which is `"S"[1][2]` -- what is it supposed to do? – avysk Feb 23 '17 at 11:31
  • Possible duplicate of [Output first 100 characters in a string](http://stackoverflow.com/questions/3486384/output-first-100-characters-in-a-string) – Teemu Risikko Feb 23 '17 at 11:32
  • Its a very simple question and yes the user should spend more time learning the language, ,but its still a valid question. What the user is *trying to do* is print (surname[0]+surname[1]+surname[2]) , which is a valid but terrible way to do it , and as the accepted answer suggests surname[0:3] is the pythonic and sensible way. OP: What your surname[0][1][2] is ACTUALLY doing is saying "Give me the third component of the second compent of the first components of surname" and the first component of Surname is the letter S, and there is no sub-components of S. but Surname[0:3]asks for a range. – Shayne Jun 29 '22 at 06:47

1 Answers1

4

You can't just put the indices [0][1][2] right after each other - that does something completely different (and requires multidimensional arrays). What you need to do it something like:

print(surname[0:3])

This will print out 3 characters from surname starting at 0 (that is to say the first 3 characters)

heroworkshop
  • 365
  • 2
  • 6