Python program to Extract string till first Non-Alphanumeric character

Python program to Extract string till first Non-Alphanumeric character

In this tutorial, we will write a Python program to extract a substring from a given string up to the first occurrence of a non-alphanumeric character.

Objective:

Given a string, extract a substring starting from the beginning of the string and ending just before the first non-alphanumeric character.

Example:

For the string:

"hello!world" 

The extracted substring will be:

"hello" 

Python Program:

def extract_till_first_non_alphanumeric(s): # Using list comprehension to get substring until the first non-alphanumeric character extracted = ''.join([char for char in s if char.isalnum() or not extracted]) return extracted # Test the function sample_string = "hello!world" result = extract_till_first_non_alphanumeric(sample_string) # Print the result print(f"Original String: {sample_string}") print(f"Extracted Substring: {result}") 

When you run the program, you'll get:

Original String: hello!world Extracted Substring: hello 

Explanation:

  1. We define a function extract_till_first_non_alphanumeric that takes a string s as its argument.
  2. We use a list comprehension to iterate through each character in the string.
  3. We append the character to our result if it is alphanumeric or if we haven't added any non-alphanumeric characters yet.
  4. The function returns the joined characters as the extracted substring.
  5. We test the function using a sample string and print the results.

Note: The condition or not extracted is used to continue appending alphanumeric characters until the first non-alphanumeric character is encountered. Once a non-alphanumeric character is appended, this condition will always be False, so the list comprehension will stop.

This program efficiently extracts a substring from a given string up to the first occurrence of a non-alphanumeric character using list comprehensions.


More Tags

fluent-interface rtmp sonar-runner sql-drop dbcontext response unity3d-gui graph algorithm getelementbyid

More Programming Guides

Other Guides

More Programming Examples