Search code examples
pythonpython-3.xstringstring-iteration

String Iteration in Python


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)

Solution

  • 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