How do you writ a for(i = 0; i < listName.lenth; i++) on Python?

Viewed 50

When doing programming on java or C++, I use this form of for loop:

for(i = 0; i < listName.length; i++)

It was giving red squiggly lines, so I did some search online. From what it looks, there is no existence of this for loop method in python. I am resorting to the 'for letter in listName' and while loops, but have not been able to substitute the above for loop in java or C++ successfully. I have included a code that gets half of the expected outcome.

code:

email = input("Please enter an email: ")

letterList = [*email]
  
for letter2 in letterList:
    if(letter2 == '.'):
        for letter3 in letterList:
            if(letter3 == '@'):
                for letterStop in letterList:
                
                        if letterStop == '.':
                            break
                        else:
                            print(letterStop)

This is the output of the above code when jason@gmail.com gets entered:

j
a
s
o
n
@
g
m
a
i
l

Input:

jason@gmail.com

Expected output:

gmail
2 Answers

For loops exist in Python, they just have a different syntax.

for i in range(len(my_string_or_list)):
    print(my_string_or_list[i])

for i,v in enumerate(my_string_or_list):
    print(f"Index {i} contains {v}")

You can use the re module (regular expression) to extract the separate portions of an email address string into a list, then get gmail from there:

import re
re.split(r"[@.]", "jason@gmail.com")[1] # 'gmail'

Loop you are talking about "for(i = 0; i < listName.length; i++)" exists in python, but it's a bit different. and it would go like this "for i in range(len(yourlist):". I see you are making a list out of string "letterList = [*email]", but you don't have to do that in python. In python string are iterable, so you can "for i in email:" and you would get every character.

Easiest way to get gmail out of email would be using split() function like this.

email = "jason@gmail.com"

a = email.split("@")[1]
b = a.split(".")[0]

print(b)

In a variable we split the email in two strings, one before @ "jason" and one after "gmail.com". After that we split "gmail.com" into two strings.

Related