A method of processing letters and numbers in python, one letter at a time, and one number at a time.

Asked 2 years ago, Updated 2 years ago, 17 views

As the title suggests,
I would like to process each letter from a sentence with mixed letters and numbers until the next letter comes out.
The code is python.

For example,

def printer(letter):
    # essentially some sort of treatment
    print(letter)

sentence="Today 19 Tomorrow 20"
For letter insence:
    if not letter.isdecimal():
        printer(letter)
    else:
        printer(letter)

Then,

 _yomi
oh!
U
Is
1
9
Ah
si
It was
Is
2
0

Yes, but

 _yomi
oh!
U
Is
19
Ah
si
It was
Is
20

I would like to know how to handle it.

python

2022-09-29 22:51

2 Answers

For example, if you use a regular expression, you can do it like this.(It's python3)

import re

def printer (letter):
    # essentially some sort of treatment
    print(letter)

sentence="Today 19 Tomorrow 20"

for match in re.findall ('[0-9]+|[^0-9]', sentence):
    printer (match)

Results:

 _yomi
oh!
U
Is
19
Ah
si
It was
Is
20


2022-09-29 22:51

I tried using re.split().

import re

def printer (letter):
  # essentially some sort of treatment
  print(letter)

sentence="Today 19 Tomorrow 20"
## Sentence = "Today 19 Tomorrow 20"
[printer(c) for core.split('(\d+|\D)', sentence) if c not in [None, ']]]

Incidentally, we use \d as a regular expression, but python 3 also matches U+FF10 to U+FF19 (if you add flags=re.ASCII to the argument re.split()).


2022-09-29 22:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.