Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

slice - How would I print everything in a string up until the first number in python?

I have an input file containing lines like the following:

"Kansas City Chiefs 42"

Each line contains a random number of spaces between the words and the numbers. I am trying to identify a way that I can slice the two values (word portion and number portion). My ideal output would be:

"Kansas City Chiefs"

"42"

Any ideas?

question from:https://stackoverflow.com/questions/65880098/how-would-i-print-everything-in-a-string-up-until-the-first-number-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Checkout this regex:

import re

your_string = "Kansas City Chiefs 42"
items = re.split(r's+(?=d)|(?<=d)s+', your_string)

print(items)

you got:

['Kansas City Chiefs', '42']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...