-3

For example, if I entered "Harry Potter" into the following code. What should I write in the blank spaces so that First_letter will be assigned with H, Second_letter with a, etc.

If possible, please also explain how the code works.

Any help will be greatly appreciated!

Name = input("Enter your name")

First_letter = ____
Second_letter = ____
Third_letter = ____
0x90
  • 39,472
  • 36
  • 165
  • 245
Iris Ho
  • 37
  • 1
  • 2
  • 6

2 Answers2

1

The easiest solution for beginners to understand in my opinion is using list() like:

>>> name = list(input("Enter your name"))
>>> name
['n', 'a', 'm', 'e']
>>> First_letter = name[0]
>>> Second_letter = name[1]
>>> Third_letter = name[2]
Idos
  • 15,053
  • 14
  • 60
  • 75
  • 2
    you don't need to convert `str` to `list`. You could do the same with `str` – Anton Protopopov Jan 14 '16 at 06:35
  • I know, but I figured he wanted to actually have characters, and also I believe it's better practice to show him this. – Idos Jan 14 '16 at 06:36
  • 1
    That's not better practice. The call to `list` makes it overly complicated. – Matthias Jan 14 '16 at 07:12
  • I don't disagree that just using the index is less complicated, But I do think that in the future, should he switch to Java/C# or basically any other language, performing such manipulations on Strings might not be possible and could cause harm. This answer is my opinion of how I would do it. It is obviously not the only answer, though it is correct nonetheless. – Idos Jan 14 '16 at 07:15
  • Unless you specifically require a list, there's no need to convert string to it, because you can use indices, slices and `for` loop over strings the same way as if it were a list. Basically, treat string as yet another sequence type in Python. And just because some other language lacks such features, it is not an excuse to dismiss them in Python. Whatever language you use, you should do things in the idiomatic way of that particular language. – Audrius Kažukauskas Jan 14 '16 at 09:05
1

You could use index for str objects:

Name = input("Enter your name")

First_letter = Name[0]
Second_letter = Name[1]
Third_letter = Name[2]
Anton Protopopov
  • 30,354
  • 12
  • 88
  • 93