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 for Convert characters of a string to opposite case
Next article icon

Python program to Extract string till first Non-Alphanumeric character

Last Updated : 22 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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))
 
 
Output
The 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))
 
 
Output
The original string is : geeks4g!!!eeks The resultant string : geeks4g

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #3 : Using for loops

Approach

  1. Initiate a for loop to access characters of string
  2. If the character is not alphanumeric append characters to output string
  3. If the character is alphanumeric break the loop
  4. 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))
 
 
Output
The 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))
 
 
Output
The 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))
 
 
Output
The 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.



Next Article
Python Program for Convert characters of a string to opposite case
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

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 module.
    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
    7 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 mo
    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 fi
    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
    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
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