python 我如何使用startswith而不指定特定的字符串?有其他选择吗?

x7yiwoj4  于 2023-03-28  发布在  Python
关注(0)|答案(6)|浏览(137)

我想把vocal_start应用到这么多不同的变量上,我不能处理所有的变量,我也不会总是重复startswith。所以我不想写variable1.startswith(("a", "e", "i", "o", "u")),但是我想应用startswith((“a”,“e”,“i”,“o”,“u”))直接指向所有变量,而不指定variable1.startswith(类似于我的代码)。
我猜使用startswith就像这样(variable1.startswith),那么还有什么我可以使用的吗?我需要一些像我的代码一样的东西,但不是用startswith(或者如果可能的话,我想用不同的startswith)

vocal_start = startswith(("a", "e", "i", "o", "u"))

variable1 = "open"

#Only for Test
if variable1 == vocal_start:
    print("correct")

当然,在代码中,我得到了NameError: name 'startswith' is not defined,因为我没有指定variable1.startswith((“a”,“e”,“i”,“o”,“u”)),但正如我所说,我不想走这条路

brccelvz

brccelvz1#

如果要检查的值都是1个字符(或长度相同),则可以使用in运算符和一个子字符串来获取第一个字母:

if variable[:1] in ("a", "e", "i", "o", "u"):
   ...

if variable[:1] in "aeiou":
   ...
v440hwme

v440hwme2#

你可以写一个function来检查提供的字符串是否以元音开头:

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")
xxe27gdn

xxe27gdn3#

这很傻,但你可以使用operator.methodcaller来创建一个函数,该函数在任何变量上调用,将使用提供的参数调用命名的方法,例如:

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

需要明确的是,没有理由这样做。这只是在代码中不必要地分割程序逻辑的简单部分,而不是将其保持在一起。在真实的的代码中,我会这样做:

if variable.startswith(('a', 'e', 'i', 'o', 'u')):

或者如果要使用的前缀集在多个地方使用并且足够长以值得分解:

vowels = ('a', 'e', 'i', 'o', 'u')  # Done once at top level

# Done each place that needs the test
if variable.startswith(vowels):
    ...
lsmepo6l

lsmepo6l4#

如果你不介意写一些晦涩难懂的代码,你可以让你想要的形式工作,写一个类,它的__eq__可以做你想要的事情,然后用这个类的一个示例来比较。

>>> class Startswith:
...     def __eq__(self, rhs):
...             return rhs.startswith(('a', 'e', 'i', 'o', 'u'))
... 
>>> startswith = Startswith()
>>> "abcd" == startswith
True
>>> "xxx" == startswith
False
dffbzjpn

dffbzjpn5#

def vowelstart(s):
    
    if(s[0].lower() in ("a", "e", "i", "o", "u")):
    
        return True
    
    return False

编辑数量

f1tvaqid

f1tvaqid6#

使用regex而不是startswith()怎么样?正则表达式的实现可能如下所示:

import re

variable1 = "open"

if re.match(r"^[aeiou]", variable1):
  print("correct")

关于r"^[aeiou]"

  • r" ... "是一个raw string,通常用于正则表达式模式。
  • 正则表达式模式中的^简单地表示 * 以 * 开头。
  • [aeiou]是一组允许的字符。

我可能会将正则表达式 Package 在一个函数中,以使其更具可读性和 pythonic。如果函数经常使用,在函数外部编译模式可能会提高性能:

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")

我希望这对你有帮助。

相关问题