This question already has answers here:
Format output string, right alignment
(8 answers)
Closed 8 years ago.
I have a tuple contains both string and float values (which are read from a txt file and calculated by me, respectively) and I want to write it to another txt file.
variables = (line.split()[0],line.split()[1], velocity) #velocity is a floating number, others are #string
output_file.write('%s %s %4.2f \n' % variables)
These lines are in a for loop. I want to align each variable in each line as right justified. How can I do that?
Please note that string items don't have same character in each line.
Python has several ways to format strings. In the form you use, you get right alignment by specifying a field length and optional padding. Python right aligns to fit the field length by default. Your float calculation already has a field length, so just decide on a length for the strings also. Its easy if you already have a max field size in mind. Here is an example of 10 spaces per string:
'%10s %10s %4.2f \n' % variables
Related
This question already has answers here:
How to remove leading and trailing zeros in a string? Python
(7 answers)
Closed last year.
I'm having issues skipping or trimming the first two numbers in a provided argument.
As an example I am passing the value of "00123456" to 'id'. I want the request.args.get against 123456 instead 00123456. is there a function I can use to drop off the zero's. Also relatively new to the python world so please advise if I need to provide more info.
#main.route('/test')
def test():
"""
Test route for validating number
example - /test?id=00123456
"""
# Get number passed in id argument
varNum = request.args.get('id')
You can convert the "00123456" to an int and it will remove all the zeros at the start of the string.
print(int("00123456"))
output:
123456
Edit:
Use this only if you want to remove any zeros at the start of the number, if you want to remove the first two chars use string slicing.
Also, use this only if u know for sure that the str will only contain numbers.
You can use string slicing, if you know that there are always two zeroes:
varNum = request.args.get('id')[2:]
Alternatively, you can use .lstrip(), if you don't know how many leading zeroes there are in advance:
varNum = request.args.get('id').lstrip('0')
This question already has answers here:
How can I convert a string with dot and comma into a float in Python
(9 answers)
Closed 5 months ago.
I am given a csv file which contains numbers ranging from 800 to 3000. The problem is numbers greater than thousand has a comma in them e.g. 1,227 or 1,074 or 2,403.
When I want to calculate their mean, variance or standard deviation using scipy or numpy, I get error: ValueError: could not convert string to float: '1,227'. How convert them to numbers so that I could do calculations on them. CSV file should not be changed as it is read only file.
Thanks, guys! I fixed it by using replace function. hpaulj's link was useful.
my_string=[val[2] for val in csvtext]
my_string=[x.replace(',', '') for x in my_string]
my_float=[float(i) for i in my_string]
This is the code, in which, 1st line loads csv string list to my_string and 2nd line removes comma and 3rd line produces numbers that are easy for calculation. So, there is no need for editing the file or creating a new one. Just a list manipulation will do the job.
This really is a locale issue, but a simple solution would be to simply call replace on the string first:
a = '1,274'
float(a.replace(',','')) # 1274.0
Another way is to use pandas to read the csv file. Its read_csv function has a thousands argument.
If you do know something about the locale, then it's probably best to use the locale.atof() function
This question already has answers here:
How to use python numpy.savetxt to write strings and float number to an ASCII file?
(3 answers)
Closed 6 years ago.
I am trying to save my data into csv file and I would like to specify different data types for different columns I am saving (e.g int for id, string for name), how can I do that?
For now with the following method I am able to save all 3 arrays as string.
d = np.column_stack((id, first_name, surname ))
np.savetxt('table.csv', d, delimiter=',', fmt="%s")
Thank you!
If all you're looking for is simply different way to format the output strings, you can look at the documentation (https://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html):
fmt : str or sequence of strs, optional
A single format (%10.5f), a sequence of formats, or a multi-format string, e.g. ‘Iteration %d – %10.5f’, in which case delimiter is
ignored.
Just pass fmt as a list of formats, e.g. fmt=("%d", "%s", "%s").
This question already has answers here:
Slicing strings in str.format
(6 answers)
Closed 6 years ago.
How can I do variable string slicing inside string.format like this.
"{0[:2]} Some text {0[2:4]} some text".format("123456")
Result I want result like this.
12 Some text 34 some text
You can't. Best you can do is limit how many characters of a string are printed (roughly equivalent to specifying a slice end), but you can't specify arbitrary start or end indices.
Save the data to a named variable and pass the slices to the format method, it's more readable, more intuitive, and easier for the parser to identify errors when they occur:
mystr = "123456"
"{} Some text {} some text".format(mystr[:2], mystr[2:4])
You could move some of the work from that to the format string if you really wanted to, but it's not a huge improvement (and in fact, involves larger temporaries when a slice ends up being needed anyway):
"{:.2s} Some text {:.2s} some text".format(mystr, mystr[2:])
This question already has answers here:
String formatting: % vs. .format vs. f-string literal
(16 answers)
Closed 8 years ago.
I find it takes quite a bit of focus, time an effort to format a string with the syntax I'm currently using:
myList=['one','two','three']
myString='The number %s is larger than %s but smaller than %s.'%(myList[1],myList[0],myList[2])
Result:
"The number two is larger than one but smaller than three"
Strange but every time I reach % keyboard key followed by s I feel kind of interrupted...
I wonder if there is alternative way of achieving a similar string formatting. Please post some examples.
You may be looking for str.format, the new, preferred way to perform string formatting operations:
>>> myList=['one','two','three']
>>> 'The number {1} is larger than {0} but smaller than {2}.'.format(*myList)
'The number two is larger than one but smaller than three.'
>>>
The main advantage of this method is that, instead of doing (myList[1],myList[0],myList[2]), you can simply unpack myList by doing *myList. Then, by numbering the format fields, you can put the substrings in the order you want.
Note too that numbering the format fields is unnecessary if myList is already in order:
>>> myList=['two','one','three']
>>> 'The number {} is larger than {} but smaller than {}.'.format(*myList)
'The number two is larger than one but smaller than three.'
>>>