Hướng dẫn split alphanumeric string python

I am trying to split and then join the first alphanumeric occurrence by space and keep other occurrences as it is, but not getting the pattern to do that. For ex: string: Johnson12 is at club39 converted_string: Jhonson 12 is at club39

Desired Output:

input = "Brijesh Tiwari810663 A14082014RGUBWA"

output = Brijesh Tiwari 810663 A14082014RGUBWA

Code:

import re
regex = re.compile["[0-9]{1,}"]
testString = "Brijesh Tiwari810663 A14082014RGUBWA" # fill this in
a = re.split['[[^a-zA-Z0-9]]', testString]
print[a]
>> ['Brijesh', ' ', 'Tiwari810663', ' ', 'A14082014RGUBWA']

asked Oct 12, 2021 at 7:16

0

Here is one way. We can use re.findall on the pattern [A-Za-z]+|[0-9]+, which will alternatively find all letter or all number words. Then, join that resulting list by space to get your output

inp = "Brijesh Tiwari810663 A14082014RGUBWA"
output = ' '.join[re.findall[r'[A-Za-z]+|[0-9]+', inp]]
print[output]  # Brijesh Tiwari 810663 A 14082014 RGUBWA

Edit: For your updated requirement, use re.sub with just one replacement:

inp = "Johnson12 is at club39"
output = re.sub[r'\b[[A-Za-z]+][[0-9]+]\b', r'\1 \2', inp, 1]
print[output]  # Johnson 12 is at club39

answered Oct 12, 2021 at 7:21

Tim BiegeleisenTim Biegeleisen

470k24 gold badges253 silver badges330 bronze badges

7

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.

Nội dung chính

  • Method 1: re.split[]
  • Method 2: re.findall[]
  • Method 3: itertools.groupby[]
  • Related Video re.split[]
  • Programmer Humor
  • Where to Go From Here?
  • How do you split a string between letters and digits?
  • How do you split an alphanumeric string in Python?
  • How do you split a string after a specific character in Python?
  • How do I extract a string between two characters in Python?

Examples: Have a look at the following examples of what you want to accomplish.

'111A222B333C'     – ->    ['111', 'A', '222', 'B', '333', 'C']
'Finxter42'        – ->    ['Finxter', '42']
'Hello world'     – ->    ['Hello', ' world']

How to Split a String Between Numbers and Letters?

  • Method 1: re.split[]
  • Method 2: re.findall[]
  • Method 3: itertools.groupby[]
  • Related Video re.split[]
  • Programmer Humor
  • Where to Go From Here?

Method 1: re.split[]

The re.split[pattern, string] method matches all occurrences of the pattern in the string and divides the string along the matches resulting in a list of strings between the matches. For example, re.split['a', 'bbabbbab'] results in the list of strings ['bb', 'bbb', 'b'].

# Method 1: re.split[]
import re
s = '111A222B333C'
res = re.split['[\d+]', s]
print[res]
# ['', '111', 'A', '222', 'B', '333', ' C']

The \d special character matches any digit between 0 and 9. By using the maximal number of digits as a delimiter, you split along the digit-word boundary. Note that you don’t consume the split character by wrapping it into a matching group using the parentheses [...]. If you leave out the parentheses, it’ll consume the numbers and the result wouldn’t contain any consecutive numbers.

Method 2: re.findall[]

The re.findall[pattern, string] method scans string from left to right, searching for all non-overlapping matches of the pattern. It returns a list of strings in the matching order when scanning the string from left to right.

# Method 2: re.findall[]
import re
s = '111A222B333C'

res = re.findall['[\d+|[A-Za-z]+]', s]

print[res]
# ['111', 'A', '222', 'B', '333', 'C']
# Method 3: itertools.groupby[]
from itertools import groupby
s = '111A222B333C'

res = [''.join[g] for _, g in groupby[s, str.isalpha]]
print[res]
# ['111', 'A', '222', 'B', '333', 'C']
  • The itertools.groupby[iterable, key=None] function creates an iterator that returns tuples [key, group-iterator] grouped by each value of key. We use the str.isalpha[] function as key function.
  • The str.isalpha[] function returns True if the string consists only of alphabetic characters.

Python Regex Split - The Complete Guide

Programmer Humor

There are only 10 kinds of people in this world: those who know binary and those who don’t.
👩🧔‍♂️
~~~

There are 10 types of people in the world. Those who understand trinary, those who don’t, and those who mistake it for binary.


👩🧔‍♂️👱‍♀️

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners [NoStarch 2020], coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

How do you split a string between letters and digits?

Steps :.

Calculate the length of the string..

Scan every character[ch] of a string one by one. if [ch is a digit] then append it in res1 string. ... .

Print all the strings, we will have one string containing a numeric part, other non-numeric part, and the last one contains special characters..

How do you split an alphanumeric string in Python?

Split a string with delimiters in Python.

Using re. split[] function. A simple solution to split a string by the pattern's occurrences is using the built-in function re.split[] . The pattern can consist of one or more delimiters: ... .

Using re. findall[] function. Another alternative is to use the re..

How do you split a string after a specific character in Python?

Python String split[] Method Syntax separator : This is a delimiter. The string splits at this specified separator. If is not provided then any white space is a separator. maxsplit : It is a number, which tells us to split the string into maximum of provided number of times.

How do I extract a string between two characters in Python?

Extract substring between two markers using split[] method Next method that we will be using is the split[] method of Python Programming language, to extract a given substring between two markers. The split[] method in python splits the given string from a given separator and returns a list of splited substrings.

Chủ Đề