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
427 views
in Technique[技术] by (71.8m points)

python 3 parsing a semicolon separated very long string to remove each second element

I'm pretty new to python and are looking for a way to get the following result from a long string reading in lines of a textfile where each line looks like this

; 2:55:12;PuffDG;66,81; Puff4OG;66,75; Puff3OG;35,38; 

after dataprocessing the data shall be stored in another textfile with this data

short example

2:55:12;66,81;66,75;35,38;        

the real string is much longer but always with the same pattern

; 2:55:12;PuffDG;66,81; Puff4OG;66,75; Puff3OG;35,38; Puff2OG;30,25; Puff1OG;29,25; PuffFB;23,50; .... 

So this means remove leading semicolon keep second element

remove third element

keep fourth element

remove fith element

keep sixth element

and so on

the number of elements can vary so I guess as a first step I have to parse the string to get the number of elements and then do some looping through the string and assign each part that shall be kept to a variable

I have tried some variations of the command .split() but with no success. Would it be easier to store all elements in a list and then for-loop through the list keeping and dropping elements?

If Yes how would this look like so at the end I have stored a file with lines like this

2:55:12 ; 66,81 ; 66,75 ; 35,38 ;

2:56:12 ; 67,15 ; 74;16 ; 39,15 ;

etc. ....

best regards Stefan

question from:https://stackoverflow.com/questions/65641009/python-3-parsing-a-semicolon-separated-very-long-string-to-remove-each-second-el

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

1 Reply

0 votes
by (71.8m points)

This solution works independently of the content between the semicolons

One line, though it's a bit messier:

result = ' ; '.join(string.split(';')[1::2])

Getting rid of lead semicolon:

Just slice it off!

string = string[2:]

Splitting by semicolon & every second element:

Given a string, we can split by semicolon:

arr = string.split(';')[1::2]

The [::2] means to slice out every second element, starting with index 1. This keeps all "even" elements (second, fourth, etcetera).

Resulting string

To produce the string result you want, simply .join:

result = ' ; '.join(arr)

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

...