
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Check if all occurrences of a character appear together in Python
Suppose we have a string s and another character c, we have to check whether all occurrences of c appear together in s or not. If the character c is not present in s then also return true.
So, if the input is like s = "bbbbaaaaaaaccddd", c = 'a', then the output will be True.
To solve this, we will follow these steps −
- flag := False
- index := 0
- n := size of string
- while index < n, do
- if string[index] is same as c, then
- if flag is True, then
- return False
- while index < n and string[index] is same as c, do
- index := index + 1
- flag := True
- if flag is True, then
- otherwise,
- index := index + 1
- if string[index] is same as c, then
- return True
Let us see the following implementation to get better understanding −
Example
def solve(string, c) : flag = False index = 0 n = len(string) while index < n: if string[index] == c: if (flag == True) : return False while index < n and string[index] == c: index += 1 flag = True else : index += 1 return True s = "bbbbaaaaaaaccddd" c = 'a' print(solve(s, c))
Input
"bbbbaaaaaaaccddd", "a"
Output
True
- Related Articles
- Python - Check if given words appear together in a list of sentence
- Count occurrences of a character in string in Python
- Java Program to replace all occurrences of a given character with new character
- Java Program to replace all occurrences of a given character in a string
- Minimize ASCII values sum after removing all occurrences of one character in C++
- How to check if a character is upper-case in Python?
- Check if all bits of a number are set in Python
- Check if all digits of a number divide it in Python
- Python Program to Replace all Occurrences of ‘a’ with $ in a String
- Program to check if a string contains any special character in Python
- Replace All Occurrences of a Python Substring with a New String?
- How to check if a character in a string is a letter in Python?
- Count occurrences of a character in a repeated string in C++
- Python program to check if a string contains any unique character
- Python - Check if all elements in a List are same

Advertisements