Examples of solving tasks with character strings. Part 1
This topic provides examples of how to solve some common problems with character strings without using the standard functions of the Python language.
Before studying the topic, it is recommended that you familiarize yourself with the topics:
- Strings. General concepts. String declaration. Operations with strings. Examples
- Escape-sequences. Unformatted strings. Multiline text blocks
- Access by indexes. Slices. Get a fragment of a string. Examples
Contents
- 1. Recursive function CountCharacterToString(). Determining the number of occurrences of a given character in a string
- 2. Function IsCharDigit(). Determine if a digit is a character specified by a position number in a string
- 3. Function IsCharOp(). Determine the number of characters +, −, *, /, % in a string
- 4. Function GetNOccurs(). Determining how many times a given string occurs in a given string
- 5. Function GetPosFirstOccur(). Determine the position (number) of the first occurrence of a substring in a string
- 6. Function IsSubstringToString(). Determining if a substring exists in a string
- Related topics
Search other websites:
1. Recursive function CountCharacterToString(). Determining the number of occurrences of a given character in a string
# Recursive function - returns the number of occurrences # of the specified character in the list def CountCharacterToString(c, s): if s=="": # loop termination condition return 0 else: if c==s[0]: # comparing a character with the first element of a string return 1 + CountCharacterToString(c, s[1:]) # recursive call else: return CountCharacterToString(c, s[1:]) # Invoke CountCharacterToString() function n = CountCharacterToString('a', "jprstaajklmnabcdadsad") print("n = ", n)
The result of the program
n = 5
⇑
2. Function IsCharDigit(). Determine if a digit is a character specified by a position number in a string
The IsCharDigit() function determines whether the character that is positioned at the specified position in the string is a digit. The function receives parameters:
- the string in which the search is carried out;
- the position number of the character to be checked.
Following are 4 ways to implement the function.
⇑
2.1. Method 1. Direct determination of the symbol’s belonging to a range of numbers
With this method, a comparison of the form is used to determine the digit
(s[index]>='0') and (s[index]<='9')
in which the determination of the belonging of an individual character s[index] to the range of numbers from ‘0’ to ‘9’ is carried out.
# Determining if there is a digit at a given position in a string def IsCharDigit(s, index): # Checking if the index value is correct if (index<0) or (index>len(s)-1): return False return (s[index]>='0')and(s[index]<='9') # Input string s = input("s = ") # Input index index = int(input("index = ")) # Display the result if IsCharDigit(s, index): print("Yes") else: print("No")
Program result
s = ABC123DEF index = 4 Yes
⇑
2.2. Method 2. Using the ord() function
In this way, you can use the ord() function, which returns the character code. The character ‘0’ has code 48, character ‘1’ has code 49, and so on. Accordingly, the character corresponding to the last digit is code 57.
Therefore, in the above example (method 1) the line fragment
(s[index]>='0')and(s[index]<='9')
can be replaced with the following line
(ord(s[index])>=48)and(ord(s[index])<=57)
⇑
2.3. Method 3. Using the standard isdigit() function
The isdigit() function from the Python library allows you to determine if a character is a digit. With this in mind, the modified version of the IsCharDigit() function has the form
# Determining if a digit is placed at a given position in a string def IsCharDigit(s, index): # Checking if the index value is correct if (index<0)or(index>len(s)-1): return False return s[index].isdigit() # Input string s = input("s = ") # Input index index = int(input("index = ")) # Display the result if IsCharDigit(s, index): print("Yes") else: print("No")
⇑
2.4. Method 4. Using the comparison string
This method is well suited for determining whether a symbol belongs to a certain set of symbols containing all possible values. Characters that make up a set of characters for comparison are formed as a string. In our case, the characters of numbers are compared, so the comparison string looks like this:
sAll = "0123456789"
The above line contains the entire set of digits of the number. According to the above, the modified IsCharDigit() function looks like this.
# Determining if a digit is placed at a specified position in a string def IsCharDigit(s, index): # Checking if the index value is correct if (index<0) or (index>len(s)-1): return False # A string containing all possible values corresponding to a digit sAll = "0123456789" # Loop search in string sAll of s[index] symbol for c in sAll: if c == s[index]: # if the character s [index] is in the set of valid characters return True return False # Input string s = input("s = ") # Input index index = int(input("index = ")) # Display the result if IsCharDigit(s, index): print("Yes") else: print("No")
⇑
3. Function IsCharOp(). Determine the number of characters +, −, *, /, % in a string
The IsCharOp() function receives a string as a parameter and determines the number of operations symbols (+, −, *, /, %) in this string. To reduce the number of comparisons, the function uses an additional line
sAll = "+-*/%"
which contains all valid operation characters.
# Determining if a digit is placed at a specified position in a string def IsCharOp(s): # A string containing all possible values that match a digit sAll = "+-*/%" # Loop for determining the number of characters in a string k = 0 # result for c1 in s: for c2 in sAll: if c1==c2: k = k+1 return k # Input string s = input("s = ") # Calculation and display the result k = IsCharOp(s) print("k = ", k)
The result of the program
s = fhg+-/*%%%++-ghjg+-% k = 13
⇑
4. Function GetNOccurs(). Determining how many times a given string occurs in a given string
4.1. Using the standard count() function
Python has a count() function that determines how many times a given substring occurs in a given string.
# Determine how many substring occurs in a string s1 = "abc abcd bcd defg bcdef" s2 = "bc" k = s1.count(s2) print("k = ", k)
The result of the program
k = 4
⇑
4.2. Solution without using the count() function
# Determine how many substring occurs in a string def GetNOccurs(sub, s): k = 0 # result index_s = 0 # position in string s from which substring search occurs while (index_s < len(s)): f_is=True # checkbox for the presence of a substring in a string index_sub = 0 # index of start of comparison in the sub string # loop search for a substring in a string while index_sub<len(sub): # checking if the end of string s has been reached if (index_s+index_sub) == len(s): f_is = False index_s = len(s)-1 break # check for mismatch of characters if s[index_s+index_sub]!=sub[index_sub]: f_is = False break else: index_sub = index_sub+1 # Checking if all characters of a string and substring match if f_is: index_s = index_s + len(sub) # processing if matched k = k+1 else: index_s = index_s+1 # processing if not matched return k # Using the GetNOccurs() function s1 = "abccc bcccca bcd" s2 = "cc" k = GetNOccurs(s2, s1) print("k = ", k)
The result of the program
k = 3
⇑
5. Function GetPosFirstOccur(). Determine the position (number) of the first occurrence of a substring in a string
Python has a number of standard functions that determine the position of a substring in a string. More details about these standard functions are described here. This example implements its own function GetPosFirstOccur(), which determines the position (number) of the first occurrence of a substring in a string.
# Determine the position of the first occurrence of a substring in a string. # The string is scanned from left to right. def GetPosFirstOccur(sub, s): index_s = 0 # position in string s from which substring search occurs while (index_s < len(s)): f_is=True # checkbox for the presence of a substring in a string index_sub = 0 # index of start of comparison in string sub # loop search for a substring in a string while index_sub<len(sub): # checking if the end of string s has been reached if (index_s+index_sub) == len(s): f_is = False index_s = len(s)-1 break # check for mismatch of characters if s[index_s+index_sub]!=sub[index_sub]: f_is = False break else: index_sub = index_sub+1 # Checking if all characters of a string and substrings match if f_is: return index_s # if matched, then return the position else: index_s = index_s+1 # processing if not matched return -1 # if no substring is found, then return -1 # Using the GetPosFirsOccur() function s1 = "abccc bcccca bcd" s2 = "cd" pos = GetPosFirstOccur(s2, s1) print("pos = ", pos)
The result of the program
pos = 14
⇑
6. Function IsSubstringToString(). Determining if a substring exists in a string
Version 1. In this function, you can call the previously developed GetNOccurs() function from paragraph 4.2. Then process the returned value k. If k>0, then the substring is in the string, if k = 0, then there is no substring in the string. The function text will be something like this:
# Function IsSubstringToString() def IsSubstringToString(sub, s): k = GetNOccurs(sub, s) # Call the function from p. 4.2. if (k==0): return False else: return True
⇑
Related topics
- Examples of solving tasks with character strings. Part 2
- Solving tasks for processing integers. Part 1
- Solving tasks for processing integers. Part 2
⇑