Python program to Extract string till first Non-Alphanumeric character
Last Updated :
22 Mar, 2023
Given a string, extract all the alphanumerics before 1st occurrence of non-alphanumeric.
Input : test_str = 'geek$s4g!!!eeks'
Output : geek
Explanation : Stopped at $ occurrence.
Input : test_str = 'ge)eks4g!!!eeks'
Output : ge
Explanation : Stopped at ) occurrence.
Method #1 : Using regex + search()
In this, search() is used to search appropriate regex() for alphanumerics, then the result is sliced till 1st occurrence of a non-alphanumeric character
Python3
# Python3 code to demonstrate working of
# Extract string till first Non-Alphanumeric character
# Using regex + search()
import re
# initializing string
test_str = 'geeks4g!!!eeks'
# printing original string
print("The original string is : " + str(test_str))
# using start() to get 1st substring
res = re.search(r'\W+', test_str).start()
res = test_str[0 : res]
# printing result
print("The resultant string : " + str(res))
OutputThe original string is : geeks4g!!!eeks
The resultant string : geeks4g
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using findall()
This is yet another regex way to solve this problem. In this, we extract the 1st substring before non-alnum character by accessing the 0th index.
Python3
# Python3 code to demonstrate working of
# Extract string till first Non-Alphanumeric character
# Using findall()
import re
# initializing string
test_str = 'geeks4g!!!eeks'
# printing original string
print("The original string is : " + str(test_str))
# using findall() to get all substrings
# 0th index gives 1st substring
res = re.findall("[\dA-Za-z]*", test_str)[0]
# printing result
print("The resultant string : " + str(res))
OutputThe original string is : geeks4g!!!eeks
The resultant string : geeks4g
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using for loops
Approach
- Initiate a for loop to access characters of string
- If the character is not alphanumeric append characters to output string
- If the character is alphanumeric break the loop
- Display the output string
Python3
# Python3 code to demonstrate working of
# Extract string till first Non-Alphanumeric character
# initializing string
test_str = 'geeks4g!!!eeks'
# printing original string
print("The original string is : " + str(test_str))
alphabets="abcdefghijklmnopqrstuvwxyz"
digits="0123456789"
res=""
for i in test_str:
if i not in alphabets+digits:
break
else:
res+=i
# printing result
print("The resultant string : " + str(res))
OutputThe original string is : geeks4g!!!eeks
The resultant string : geeks4g
Time Complexity : O(N)
Auxiliary Space : O(N)
Method #4: Using string slicing
This method uses a for loop to iterate through the characters in the string, and checks if each character is alphanumeric using the isalnum() method. If it encounters a non-alphanumeric character, it extracts the substring of the original string up to that character using string slicing (test_str[:i]). If there are no non-alphanumeric characters in the string, it simply returns the original string.
Python3
# Python3 code to demonstrate working of
# Extract string till first Non-Alphanumeric character
# initializing string
test_str = 'geeks4g!!!eeks'
# printing original string
print("The original string is : " + str(test_str))
# Method #4: Using string slicing
for i in range(len(test_str)):
if not test_str[i].isalnum():
res = test_str[:i]
break
else:
res = test_str
# printing result
print("The resultant string : " + str(res))
OutputThe original string is : geeks4g!!!eeks
The resultant string : geeks4g
Time Complexity : O(N), where N is length of test_str
Auxiliary Space : O(N)
Method#5: Using Recursive method.
This implementation uses a recursive function extract_string that takes in a string as input and returns the extracted string. If the input string is empty or the first character is non-alphanumeric, it returns an empty string. Otherwise, it returns the first character concatenated with the result of calling the function recursively with the remaining substring.
Python3
# Python3 code to demonstrate working of
# Extract string till first Non-Alphanumeric character
def extract_string(string):
if not string or not string[0].isalnum():
return ""
return string[0] + extract_string(string[1:])
# initializing string
test_str = 'geeks4g!!!eeks'
# printing original string
print("The original string is : " + str(test_str))
res = extract_string(test_str)
# printing result
print("The resultant string : " + str(res))
OutputThe original string is : geeks4g!!!eeks
The resultant string : geeks4g
Note that this implementation can be inefficient for very long input strings, as it creates a new substring on each recursive call.
The time complexity is O(n) where n is the length of the input string.
The space complexity is also O(n) due to the recursive call stack.
Similar Reads
Python Regex | Program to accept string ending with alphanumeric character
Prerequisite: Regular expression in PythonGiven a string, write a Python program to check whether the given string is ending with only alphanumeric character or Not.Examples:Â Â Input: ankitrai326 Output: Accept Input: ankirai@ Output: Discard In this program, we are using search() method of re modul
2 min read
Python program to extract characters in given range from a string list
Given a Strings List, extract characters in index range spanning entire Strings list. Input : test_list = ["geeksforgeeks", "is", "best", "for", "geeks"], strt, end = 14, 20 Output : sbest Explanation : Once concatenated, 14 - 20 range is extracted.Input : test_list = ["geeksforgeeks", "is", "best",
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
6 min read
Python program to remove the nth index character from a non-empty string
Given a String, the task is to write a Python program to remove the nth index character from a non-empty string Examples: Input: str = "Stable" Output: Modified string after removing 4 th character Stabe Input: str = "Arrow" Output: Modified string after removing 4 th character Arro The first approa
4 min read
Python program to remove last N characters from a string
In this article, weâll explore different ways to remove the last N characters from a string in Python. This common string manipulation task can be achieved using slicing, loops, or built-in methods for efficient and flexible solutions.Using String SlicingString slicing is one of the simplest and mos
2 min read
How to Capitalize First Character of String in Python
Suppose we are given a string and we need to capitalize the first character of it, for example:Input: "geeks"Output: "Geeks"In this article, we are going to learn several ways of doing it with examples, let's look at them:Using str.capitalize()Using str.capitalize() is a simple way to make the first
2 min read
Python program to print k characters then skip k characters in a string
Given a String, extract K characters alternatively. Input : test_str = 'geeksgeeksisbestforgeeks', K = 4 Output : geekksisforg Explanation : Every 4th alternate range is sliced. Input : test_str = 'geeksgeeksisbest', K = 4 Output : geekksis Explanation : Every 4th alternate range is sliced. Method #
5 min read
Python program for removing i-th character from a string
In this article, we will explore different methods for removing the i-th character from a string in Python. The simplest method involves using string slicing.Using String SlicingString slicing allows us to create a substring by specifying the start and end index. Here, we use two slices to exclude t
2 min read
Python - Extract String till all occurrence of characters from other string
Given a string, the task is to write a Python program to extract till all characters from other strings are found. Input : test_str = "geeksforgeeks is best for all geeks", check_str = "freak"Output : geeksforgeeks is best for aExplanation : a is last letter in freak to be present in string. The str
11 min read
Python - Extract String after Nth occurrence of K character
Given a String, extract the string after Nth occurrence of a character. Input : test_str = 'geekforgeeks', K = "e", N = 2 Output : kforgeeks Explanation : After 2nd occur. of "e" string is extracted. Input : test_str = 'geekforgeeks', K = "e", N = 4 Output : ks Explanation : After 4th occur. of "e"
7 min read