sebway
sebway

Reputation: 33

Split string of numbers with no whitespaces in python

I have a string of numbers with no whitespaces like this:

s = '12.2321.4310.85'

I know that the format for each number is F5.2 (I am reading the string from a FORTRAN code output)

I need to obtain the following list of numbers based on s:

[12.23,21.43,10.85]

How can I do this in python?

Thanks in advance for any help!

Upvotes: 0

Views: 81

Answers (3)

aminrd
aminrd

Reputation: 5000

I think the safest way is to rely on . points. Because we know that every floating point should have one fraction and always there are two fraction numbers (there might be values like 1234.56 and 78.99 in the data that generates s = "1234.5678.99"). But we are not sure how many digits are before .. So we can extract values one by one based on ..

s = '12.2321.4310.85'
def extractFloat(s):
    # Extracts the first floating number with 2 floatings from the string
    return float( s[:s.find('.')+3]) , s[s.find('.')+3:]

l = []
while len(s) > 0:
    value, s = extractFloat(s)
    l.append(value)

print(l)
# Output: 
# [12.23, 21.43, 10.85]

Upvotes: 0

Prune
Prune

Reputation: 77847

Slice the string into chunks of 5 characters. Convert each chunk to float.

>>> [float(s[i:i+5]) for i in range(0, len(s), 5)]
[12.23, 21.43, 10.85]

Upvotes: 3

Celius Stingher
Celius Stingher

Reputation: 18367

If you are really sure of the format, and that will always be handed in that way then using a step of 5 in your loop might work:

s = '12.2321.4310.85'
output = []
for i in range(0,len(s),5):
    output.append(float(s[i:i+5]))
print(output)

Output:

[12.23, 21.43, 10.85]

Upvotes: 0

Related Questions