1

So the question I was trying to solve is

"Print the first 4 letters of name on new line [name = 'Hiroto']"

I got a solution, but I was wondering if there was a way to do the same problem using index values to make it work with any name I used.

name = "Hiroto"

new_name = " "

for letter in name:
    if letter != "t":
        new_name = new_name + letter
    if letter == "t":
        print(new_name)

3 Answers3

3

You can use the slice operator. string[i:j] will return a new string that includes the characters from, and including, index i up to, but not including the character at index j.

Example:

>>> name = "Hiroto"

>>> print(name[0:4])

Will print:

Hiro
devjoco
  • 425
  • 3
  • 15
0

What you are doing is concatenating characters into one variable, you condition is until you hit a 't', in your case the 5th letter, so that will only work for that name.

As others pointed out you can do name[0:4] (from index zero to four included), you could even ignore the 0 and use name[:4]. This operation is called slicing.

But if you want to keep the same logic as your solution you can just use a counter variable . I created a function that does receives a name and returns the first 4 letters:

def first_4_letters(name):
    new_name = ""
    count = 0
    while count < 4:
        new_name = new_name + name[count]

print(first_4_letters('Hiroto'))
  • Thanks for this, this is along the lines of what I was trying to achieve initially since I didn't think about slicing. It's only my third day of coding so it's still a lot to try and think of. Really helpful though. I do have one question though, 'count' isn't defined in your code, does it self define as a variable or is it an argument built into Python? – Conner Williams Apr 10 '20 at 18:41
  • I defined count in the third line count = 0 It is a variable inside a function. An argument is an input variable of a function, in the example name. You can loop using a for statement or a while statement. When you are trying to iterate a string, list, etc a for statement is recommended, we say it is more pythonic. You use a while statement to loop as long the condition you set is True. – Mariano Montero Apr 11 '20 at 04:43
0

you can also use this alternative way...

name = "Hiroto"
i=0
while i < len(name):
     print(name[i])##Hiro
     i=i+1
     if i==4:
         break

when your string reaches the index (i==4) then it break the loop and exit...

Lakshmi Ram
  • 11
  • 1
  • 7