I’m pretty new to Python programming and would appreciate some help to a problem I have…
Basically I have multiple text files which contain velocity values as such:
0.259515E+03 0.235095E+03 0.208262E+03 0.230223E+03 0.267333E+03 0.217889E+03 0.156233E+03 0.144876E+03 0.136187E+03 0.137865E+00
etc for many lines…
What I need to do is convert all the values in the text file that are less than 1 (e.g. 0.137865E+00 above) to an arbitrary value of 0.100000E+01. While it seems pretty simple to replace specific values with the ‘replace()’ method and a while loop, how do you do this if you want to replace a range?
thanks
I think when you are beginning programming, it’s useful to see some examples; and I assume you’ve tried this problem on your own first!
Here is a break-down of how you could approach this:
The split method works on strings. It returns a list of strings. By default, it splits on whitespace:
The map command applies its first argument (the function
float) to each of the elements of its second argument (the liststring_numbers). Thefloatfunction converts each string into a floating-point object.You can use a list comprehension to process the list, converting numbers less than 1 into the number 1. The conditional expression
(1 if num<1 else num)equals 1 when num is less than 1, otherwise, it equals num.This is the same thing, all in one line:
To generate a string out of the elements of
processed_numbers, you could use thestr.joinmethod: