Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program to Accept the Strings Which Contains all Vowels
Next article icon

Python Program to Count characters surrounding vowels

Last Updated : 20 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a String, the task is to write a Python program to count those characters which have vowels as their neighbors.

Examples:

Input : test_str = ‘geeksforgeeksforgeeks’ 
Output : 10 
Explanation : g, k, f, r, g, k, f, r, g, k have surrounding vowels.

Input : test_str = ‘geeks’ 
Output : 2 
Explanation : g, k have surrounding vowels. 
 

Method 1 : Using loop

In this, we increment counter while checking previous and successive element for vowels using loop.

Python3




# initializing string
test_str = 'geeksforgeeksforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
res = 0
vow_list = ['a', 'e', 'i', 'o', 'u']
for idx in range(1, len(test_str) - 1):
 
    # checking for preceding and succeeding element to be vowel
    if test_str[idx] not in vow_list and (test_str[idx - 1] in vow_list or test_str[idx + 1] in vow_list):
        res += 1
 
# solving for 1st and last element
if test_str[0] not in vow_list and test_str[1] in vow_list:
    res += 1
 
if test_str[-1] not in vow_list and test_str[-2] in vow_list:
    res += 1
 
# printing result
print("Characters around vowels count : " + str(res))
 
 

Output:

The original string is : geeksforgeeksforgeeks

Characters around vowels count : 10

Method 2 : Using sum() and list comprehension

In this, we perform the task of getting count using sum() and iteration and filtering is done using list comprehension.

Python3




# initializing string
test_str = 'geeksforgeeksforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
vow_list = ['a', 'e', 'i', 'o', 'u']
 
# sum() accumulates all vowels surround elements
res = sum([1 for idx in range(1, len(test_str) - 1) if test_str[idx]
           not in vow_list and (test_str[idx - 1] in vow_list or test_str[idx + 1] in vow_list)])
 
# solving for 1st and last element
if test_str[0] not in vow_list and test_str[1] in vow_list:
    res += 1
 
if test_str[-1] not in vow_list and test_str[-2] in vow_list:
    res += 1
 
# printing result
print("Characters around vowels count : " + str(res))
 
 

 Output:

The original string is : geeksforgeeksforgeeks

Characters around vowels count : 10

The time and space complexity for all the methods are the same:

Time Complexity: O(n)

Space Complexity: O(n)

Method 3: Using enumerate () method.

Python3




# initializing string
test_str = 'geeksforgeeksforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
count=0
 
#counting vowel surrounding characters using enumerate() method
 
for idx, val in enumerate(test_str):
  if val in 'aeiouAEIOU':
    if idx > 0 and test_str[idx-1] not in 'aeiouAEIOU':
      count += 1
    if idx < len(test_str) - 1 and test_str[idx+1] not in 'aeiouAEIOU':
       count += 1
 
# printing result
print("Characters around vowels count : " + str(count))
 
 
Output
The original string is : geeksforgeeksforgeeks Characters around vowels count : 10

Time Complexity:  O(n)

Auxiliary Space: O(1)

Method 4: Using Regex

Explanation
In this approach, we use the re.findall() method to find the characters that are surrounded by vowels.
The regular expression r'[^aeiouAEIOU]([aeiouAEIOU])[^aeiouAEIOU]’ matches a character that is not a vowel, followed by a vowel, followed by a character that is not a vowel.
The len() function is used to count the number of matches found.
 

Python3




#Importing the regular expression module
import re
 
#initializing string
test_str = 'geeksforgeeksforgeeks'
 
#printing original string
print("The original string is : " + str(test_str))
 
#Using re.findall() to find the number of characters surrounded by vowels
res = len(re.findall(r'[^aeiouAEIOU]([aeiouAEIOU])', test_str)) + len(re.findall(r'([aeiouAEIOU])[^aeiouAEIOU]', test_str))
 
#printing result
print("Characters around vowels count : " + str(res))
 
 
Output
The original string is : geeksforgeeksforgeeks Characters around vowels count : 10

Time Complexity: O(n)

Auxiliary Space: O(n)



Next Article
Python Program to Accept the Strings Which Contains all Vowels
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python - Convert String to unicode characters
    Convert String to Unicode characters means transforming a string into its corresponding Unicode representations. Unicode is a standard for encoding characters, assigning a unique code point to every character. For example: string "A" has the Unicode code point U+0041.string "你好" corresponds to U+4F6
    2 min read
  • Python Program to Count the Number of Vowels in a String
    In this article, we will be focusing on how to print each word of a sentence along with the number of vowels in each word using Python. Vowels in the English language are: 'a', 'e', 'i', 'o', 'u'. So our task is to calculate how many vowels are present in each word of a sentence. So let us first des
    10 min read
  • Count the number of characters in a String - Python
    The goal here is to count the number of characters in a string, which involves determining the total length of the string. For example, given a string like "GeeksForGeeks", we want to calculate how many characters it contains. Let’s explore different approaches to accomplish this. Using len()len() i
    3 min read
  • Python Program to Accept the Strings Which Contains all Vowels
    The problem is to determine if a string contains all the vowels: a, e, i, o, u. In this article, we’ll look at different ways to solve this. Using all()all() function checks if all vowels are present in the string. It returns True if every condition in the list comprehension is met. [GFGTABS] Python
    2 min read
  • Python Program to find if a character is vowel or Consonant
    Given a character, check if it is vowel or consonant. Vowels are 'a', 'e', 'i', 'o' and 'u'. All other characters ('b', 'c', 'd', 'f' ....) are consonants. Examples: Input : x = 'c'Output : ConsonantInput : x = 'u'Output : VowelRecommended: Please try your approach on {IDE} first, before moving on t
    5 min read
  • Python program to count words in a sentence
    In this article, we will explore different methods for counting words in a sentence. The split() method is one of the simplest and most efficient ways to count words in a sentence. [GFGTABS] Python s = "Python is fun and versatile." # Counting words word_count = len(s.split()) print(word_c
    2 min read
  • Python program to find occurrence to each character in given string
    Given a string, the task is to write a program in Python that prints the number of occurrences of each character in a string. There are multiple ways in Python, we can do this task. Let's discuss a few of them. Method #1: Using set() + count() Iterate over the set converted string and get the count
    5 min read
  • Python program to check if given string is vowel Palindrome
    Given a string (may contain both vowel and consonant letters), remove all consonants, then check if the resulting string is palindrome or not. Examples: Input : abcuhuvmnba Output : YES Explanation : The consonants in the string "abcuhuvmnba" are removed. Now the string becomes "auua". Input : xayzu
    5 min read
  • Python program to find the sum of Characters ascii values in String List
    Given the string list, the task is to write a Python program to compute the summation value of each character's ASCII value. Examples: Input : test_list = ["geeksforgeeks", "teaches", "discipline"] Output : [133, 61, 100] Explanation : Positional character summed to get required values. Input : test
    4 min read
  • Python Program for Convert characters of a string to opposite case
    Given a string, convert the characters of the string into the opposite case,i.e. if a character is the lower case then convert it into upper case and vice-versa. Examples: Input : geeksForgEeksOutput : GEEKSfORGeEKSInput: hello every oneOutput: HELLO EVERY ONEExample 1: Python Program for Convert ch
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences