Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 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 Reply

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']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...