How can I use startswith without specifying a certain string? Is there any alternative?
Question:
I would like to apply vocal_start
to so many different variables and i can’t handle them all and i wouldn’t always repeat startswith
. So I don’t want to write variable1.startswith(("a", "e", "i", "o", "u"))
, but i would like to apply startswith(("a", "e", "i", " o", "u")) directly to all variables without specifying variable1.startswith
(something similar to my code). I wouldn’t always repeat startswith
I guess using startswith
is only like this (variable1.startswith), so is there anything else I can use? I need something like my code, but not with startswith (or I’d like to use startswith differently if possible)
vocal_start = startswith(("a", "e", "i", "o", "u"))
variable1 = "open"
#Only for Test
if variable1 == vocal_start:
print("correct")
In the code, of course, I get the NameError: name 'startswith' is not defined
because I didn’t specify variable1.startswith(("a", "e", "i", "o", "u")), but as I said, I don’t want to go this route
Answers:
If the values to check are all 1 character (or all the same length) you could use the in
operator with a substring to get the first letter(s):
if variable[:1] in ("a", "e", "i", "o", "u"):
...
or
if variable[:1] in "aeiou":
...
You can write a function
that checks if the string provided starts with a vowel:
def starts_with_vowel(str):
return str.lower().startswith(("a", "e", "i", "o", "u")) # lower to be more general
variable1 = "open"
# check if it starts with a vowel
if starts_with_vowel(variable1):
print("correct")
You can get your desired form to work if you don’t mind writing really obscure code. Write a class whose __eq__
does what you want and then use an instance of that class for your compare.
>>> class Startswith:
... def __eq__(self, rhs):
... return rhs.startswith(('a', 'e', 'i', 'o', 'u'))
...
>>> startswith = Startswith()
>>> "abcd" == startswith
True
>>> "xxx" == startswith
False
It’s silly, but you can use operator.methodcaller
to make a function that, called on any variable, will invoke the named method with the provided arguments, e.g.:
from operator import methodcaller # At top of file
starts_with_vowel = methodcaller('startswith', ('a', 'e', 'i', 'o', 'u')) # Done once at top level
# Done whenever you need to test a given variable
if starts_with_vowel(any_variable_producing_a_string):
...
To be clear, there’s no reason to do this. It’s just needlessly splitting up simple parts of program logic across your code rather than keeping it close together. In real code, I’d just do:
if variable.startswith(('a', 'e', 'i', 'o', 'u')):
or if the set of prefixes to use is used in multiple places and long enough to be worth factoring out:
vowels = ('a', 'e', 'i', 'o', 'u') # Done once at top level
# Done each place that needs the test
if variable.startswith(vowels):
...
def vowelstart(s):
if(s[0].lower() in ("a", "e", "i", "o", "u")):
return True
return False
#Edited
How about using regex instead of startswith()
? A regular expression implementation could look like this:
import re
variable1 = "open"
if re.match(r"^[aeiou]", variable1):
print("correct")
Explanation of r"^[aeiou]"
:
r" ... "
is a raw string often used for regex patterns.
^
simply means starts with.
[aeiou]
is a set of allowed characters.
I would probably wrap the regex in a function to make it more readable and pythonic. And compiling the pattern once outside the function may improve performance if the function is used often:
import re
STARTS_WITH_VOWEL_PATTERN = re.compile(r"^[aeiou]", re.IGNORECASE)
def starts_with_vowel(text: str) -> bool:
return True if STARTS_WITH_VOWEL_PATTERN.match(text) else False
if starts_with_vowel("open"):
print("correct")
I hope this is helpful.
I would like to apply vocal_start
to so many different variables and i can’t handle them all and i wouldn’t always repeat startswith
. So I don’t want to write variable1.startswith(("a", "e", "i", "o", "u"))
, but i would like to apply startswith(("a", "e", "i", " o", "u")) directly to all variables without specifying variable1.startswith
(something similar to my code). I wouldn’t always repeat startswith
I guess using startswith
is only like this (variable1.startswith), so is there anything else I can use? I need something like my code, but not with startswith (or I’d like to use startswith differently if possible)
vocal_start = startswith(("a", "e", "i", "o", "u"))
variable1 = "open"
#Only for Test
if variable1 == vocal_start:
print("correct")
In the code, of course, I get the NameError: name 'startswith' is not defined
because I didn’t specify variable1.startswith(("a", "e", "i", "o", "u")), but as I said, I don’t want to go this route
If the values to check are all 1 character (or all the same length) you could use the in
operator with a substring to get the first letter(s):
if variable[:1] in ("a", "e", "i", "o", "u"):
...
or
if variable[:1] in "aeiou":
...
You can write a function
that checks if the string provided starts with a vowel:
def starts_with_vowel(str):
return str.lower().startswith(("a", "e", "i", "o", "u")) # lower to be more general
variable1 = "open"
# check if it starts with a vowel
if starts_with_vowel(variable1):
print("correct")
You can get your desired form to work if you don’t mind writing really obscure code. Write a class whose __eq__
does what you want and then use an instance of that class for your compare.
>>> class Startswith:
... def __eq__(self, rhs):
... return rhs.startswith(('a', 'e', 'i', 'o', 'u'))
...
>>> startswith = Startswith()
>>> "abcd" == startswith
True
>>> "xxx" == startswith
False
It’s silly, but you can use operator.methodcaller
to make a function that, called on any variable, will invoke the named method with the provided arguments, e.g.:
from operator import methodcaller # At top of file
starts_with_vowel = methodcaller('startswith', ('a', 'e', 'i', 'o', 'u')) # Done once at top level
# Done whenever you need to test a given variable
if starts_with_vowel(any_variable_producing_a_string):
...
To be clear, there’s no reason to do this. It’s just needlessly splitting up simple parts of program logic across your code rather than keeping it close together. In real code, I’d just do:
if variable.startswith(('a', 'e', 'i', 'o', 'u')):
or if the set of prefixes to use is used in multiple places and long enough to be worth factoring out:
vowels = ('a', 'e', 'i', 'o', 'u') # Done once at top level
# Done each place that needs the test
if variable.startswith(vowels):
...
def vowelstart(s):
if(s[0].lower() in ("a", "e", "i", "o", "u")):
return True
return False
#Edited
How about using regex instead of startswith()
? A regular expression implementation could look like this:
import re
variable1 = "open"
if re.match(r"^[aeiou]", variable1):
print("correct")
Explanation of r"^[aeiou]"
:
r" ... "
is a raw string often used for regex patterns.^
simply means starts with.[aeiou]
is a set of allowed characters.
I would probably wrap the regex in a function to make it more readable and pythonic. And compiling the pattern once outside the function may improve performance if the function is used often:
import re
STARTS_WITH_VOWEL_PATTERN = re.compile(r"^[aeiou]", re.IGNORECASE)
def starts_with_vowel(text: str) -> bool:
return True if STARTS_WITH_VOWEL_PATTERN.match(text) else False
if starts_with_vowel("open"):
print("correct")
I hope this is helpful.