检查字符串是否包含子字符串

时间:2021-04-17 18:27:54

标签: python string boolean contains

请帮我解决这个问题!

问题: 定义一个名为 contains_all_the_vowels(x) 的函数,该函数返回 x 是否包含所有元音(a、e、i、o、u)

这是我的代码:

def contains_all_the_vowels(x):
vo= 'aeiou'
if vo in x:
    return True
else:
    return False

它显示:

AssertionError: None is not true

3 个答案:

答案 0 :(得分:0)

不漂亮但简单。

def contains_all_the_vowels(x):
    if "a" in x and "e" in x and "i" in x and "o" in x and "u" in x:
        return True
    return False

答案 1 :(得分:0)

您正在搜索整个单词 public void onMapReady(GoogleMap googleMap) { final Marker marker2 = googleMap.addMarker(new MarkerOptions().position(new LatLng(1, 1)).snippet(FORM_VIEW)); final int offsetX = (int) getResources().getDimension(R.dimen.marker_offset_x); final int offsetY = (int) getResources().getDimension(R.dimen.marker_offset_y); final InfoWindow.MarkerSpecification markerSpec = new InfoWindow.MarkerSpecification(offsetX, offsetY); formWindow = new InfoWindow(marker2, markerSpec, new FormFragment()); googleMap.setOnMarkerClickListener(MainActivity.this); } 而不是每个字符。 改用这个:

aeiou

答案 2 :(得分:0)

Membership 检查左边的参数是否在右边的数组中。所以 "a" in "abc" 检查字符“a”是否在“abc”中。 while "abc" in "string" 检查子串“abc”是否出现在“string”

要解决您的问题,详细方法是

def contains_all_the_vowels(x):
  vo = 'aeiou'
  for c in vo:
    if c not in x:
      return False
  return True

使用列表推导式可以写成

def contains_all_the_vowels(x):
    return all([c in x for c in 'aeiou'])

使用列表推导式的方便之处在于它可以轻松处理“任何元音”或“所有元音”或“无元音”的情况,如下所示:

def contains_all_the_vowels(x):
    occurs = [c in x for c in 'aeiou']
    if all(occurs):
        return "All vowels found"
    if any(occurs):
        return "At least one vowel found"
    return "No vowels found"