Regex

How To Remove All Non-Alphabet Characters From A String?

💡 Summary: This blog explores the steps to remove all non-alphabet characters from a given string. The ‘re’ module in Python provides regular expression operations, to process text. One uses these operations to manipulate text in strings. The compile() method in conjunction with the sub() method can remove all non-alphabet characters from a given string. Note: …

How To Remove All Non-Alphabet Characters From A String? Read More »

How to Escape Special Characters of a Python String with a Single Backslash?

The backslash escape character ‘\’ is a special Python string character that is usually followed by an alphabetic character. For example, the tabular whitespace ‘\t’ and newline ‘\n’. In regular expressions, you can use the single escape to remove the special meaning of regex symbols. For example, to match the dot or asterisk characters ‘.’ …

How to Escape Special Characters of a Python String with a Single Backslash? Read More »

Python endswith() Tutorial – Can We Use Regular Expressions?

While refactoring my Python code, I thought of the following question. Can You Use a Regular Expression with the Python endswith() Method? The simple answer is no because if you can use a regex, you won’t even need endswith()! Instead, use the re.match(regex, string) function from the re module. For example, re.match(“^.*(coffee|cafe)$”, tweet) checks whether …

Python endswith() Tutorial – Can We Use Regular Expressions? Read More »

You Cannot Use Python Regex in startswith(). Do This Instead.

I’m sitting in front of my computer refactoring Python code and have just thought of the following question: Can You Use a Regular Expression with the Python string.startswith() Method? The short answer is no. The string.startswith() method doesn’t allow regular expression inputs. And you don’t need it because regular expressions can already check if a …

You Cannot Use Python Regex in startswith(). Do This Instead. Read More »

How to Find Multiple Occurrences of a String Within a String in Python?

Problem Formulation: Given a longer string and a shorter string. How to find all occurrences of the shorter string in the longer one? Consider the following example: Longer string: ‘Finxters learn Python with Finxter’ Shorter string: ‘Finxter’ Result: [‘Finxter’, ‘Finxter’] Optionally, you may also want to print the positions where the shorter string arise in …

How to Find Multiple Occurrences of a String Within a String in Python? Read More »

How to Split a String Between Numbers and Letters?

Problem Formulation: Given a string of letters and numbers. How to split the string into substrings of either letters or numbers by using the boundary between a letter and a number and vice versa. Examples: Have a look at the following examples of what you want to accomplish. ‘111A222B333C’ —> [‘111’, ‘A’, ‘222’, ‘B’, ‘333’, …

How to Split a String Between Numbers and Letters? Read More »