On 12/28/2020 11:31 AM, Bischoop wrote:
I'd like to check if there's "@" in a string
Use the obvious "'@' in string".
> and wondering if any method is better/safer than others.
Any special purpose method built into the language is likely to be
fastest. Safest? What danger are you worried about?
I was told on one occasion that I should
use is than ==, so how would be on this example.
'is' is for detecting an exact match with a particular, singular object.
In particular, None, False, or True or user created objects meant for
such use.
s = 't...@mail.is'
I want check if string is a valid email address.
There are two levels of validity: has the form of an address, which is
much more complicated than the presence of an '@', and corresponds to a
real email account.
code '''
import time
email = "t...@mail.tu"
start_time = time.time()
for i in range(len(email)):
print('@' in email[i])
This scans the entire string in a slow way, then indirectly performs '@'
== char in a slow way.
print ("My program took", time.time() - start_time, "to run")
print('----------')
start_time = time.time()
for i in range(len(email)):
print(email[i] == '@')
Slightly better, does comparison directly.
for c in email:
print(c == '@')
Faster and better way to scan.
for c in email:
print(c == '@')
break
Stops at first '@'. '@' in email does the same, but should be slightly
faster as it implements loop and break in the interpreter's
implementation language.
print ("My program took", time.time() - start_time, "to run")
print('----------')
start_time = time.time()
if '@' in email:
print('True')
print ("My program took", time.time() - start_time, "to run")
'''
--
Terry Jan Reedy
--
https://mail.python.org/mailman/listinfo/python-list