String Iteration in Python

1.4k Views Asked by At

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

There are 3 best solutions below

1
On BEST ANSWER

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
2
On

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'))
1
On

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...