string formatting with .format - python-3.x

I am trying to find the stat and p-value using shapiro function
I am formatting my results using .format but I am not able to understand why I am getting different results for below:
print ('stat = {0:.2f}'.format(stat), 'p = {0:.30f}'.format (p))
print ('stat = {0:.2f}, p = {0:.30f}'.format (stat,p))
first one prints 0.000000000000000268680677283857 (this is correct)
second one prints 0.974334061145782470703125000000

There is a mistake in the format string of the second example. Change the second format specification from {0:.30f} to {1:.30f}. With this style of formatting, when the first item in the format specification is a number, it indicates which positional argument of the format() method to print.
For example,
In [81]: stat = 0.974334061145782470703125
In [82]: p = 0.000000000000000268680677283857
In [83]: print('stat = {0:.2f}, p = {1:.30f}'.format(stat, p))
stat = 0.97, p = 0.000000000000000268680677283857
If you are using Python 3.6 or later, you might find it more convenient to use an f-string:
In [93]: print(f'stat = {stat:.2f}, p = {p:0.30f}')
stat = 0.97, p = 0.000000000000000268680677283857
The = format character allows an even more concise string expression:
In [101]: print(f'{stat = :.2f}, {p = :0.30f}')
stat = 0.97, p = 0.000000000000000268680677283857

Related

Python split currency string into currency code and amount

I am trying to split R15.49 to (R, 15.49) or
ZAR15.49 to (ZAR, 15.49)
I have tried one of the solutions here and implememted the function below:
def splitCurrency(string):
match = re.search(r'([\D]+)([\d,]+)', string)
output = (match.group(1), match.group(2).replace(',',''))
return output
But I am getting (R, 15) or (ZAR, 15). and its ignoring the digits after the decimal place
If you want to fish out these values from a larger text, then use re.findall:
inp = "R15.49 or ZAR15.49"
matches = re.findall(r'\b([A-Z]+)(\d+(?:\.\d+)?)\b', inp)
print(matches)
This prints:
[('R', '15.49'), ('ZAR', '15.49')]

Error: "can't multiply sequence by non-int of type 'float'"

It says the error is when h (altitude) is between 11000 and 25000, so I only posted the initial stuff outside all my if loops and the specific loop where the problem is happening. Here is my code:
import math;
T = 0.0;
P = 0.0;
hString = ("What is the altitude in meters?");
h = int(hString);
e = math.exp(0.000157*h);
elif 11000 < h < 25000:
T = -56.46;
P = (22.65)*[(1.73)-e];
When you use mathematical operations you need to be careful with brackets.
P = (22.65)*((1.73)-e); #will be right way of using
[ ] using will create a list which you, do not need in this program.
Here is a link which will help you learn much more about type conversions and proper use of brackets while doing mathematics on it.
Also in your code you have not used
hString =input ("What is the altitude in meters?");
h = int(hString);
input will allow you to take value from user and then int(your_input) will help you convert to integer
The square brackets in the last line ([(1.73)-e]) create a list. In this case, it's a list with one element, namely (1.73)-e. I imagine you intended those to be parens. Make that change and it will work.
The final line becomes:
P = (22.65)*((1.73)-e);

Convert ALL UPPERCASE to Title

#!/usr/bin/python3.4
import urllib.request
import os
import re
os.chdir('/home/whatever/')
a = open('Shopstxt.csv','r')
b = a.readlines()
a.close()
c = len(b)
d = list(zip(*(e.split(';') for e in b)))
shopname = []
shopaddress = []
shopcity = []
shopphone = []
shopwebsite = []
f = d[0]
g = d[1]
h = d[2]
i = d[3]
j = d[4]
e = -1
for n in range(0, 5):
e = e + 1
sn = f[n]
sn.title()
print(sn)
shopname.append(sn)
sa = g[n]
sa.title()
shopaddress.append(sa)
sc = h[n]
sc.title()
shopcity.append(sc)
Shopstxt.csv is all upper case letters and I want to convert them to title. I thought this would do it but it doesn't...it still leaves them all upper case. What am I doing wrong?
I also want to save the file back. Just wanting to check on a couple of things real quick like as well...time pressed.
When I combine the file back together, before writing it back to the drive do I have to add an '\n' at the end of each line or does it automatically include the '\n' when I write each line to the file?
Strings are immutable, so you need to asign the result of title():
sa = sa.title()
sc = sc.title()
Also, if you do this:
with open("bla.txt", "wt") as outfile:
outfile.write("stuff")
outfile.write("more stuff")
then this will not automatically add line endings.
A quick way to add line endings would be this:
textblobb = "\n".join(list_of_text_lines)
with open("bla.txt", "wt") as outfile:
outfile.write(textblobb)
As long as textblobb isn't inefficiently large and fits into memory, that should do the trick nicely.
Use the .title() method when defining your variables like I did in the code below. As others have mentioned, strings are immutable so save yourself a step and create the string you need in one line.
for n in range(0, 5):
e = e + 1
sn = f[n].title() ### Grab and modify the list index before assigning to your variable
print(sn)
shopname.append(sn)
sa = g[n].title() ###
shopaddress.append(sa)
sc = h[n].title() ###
shopcity.append(sc)

String interpolation

In scala, you easily include the content of a variable inside a string, like this:
val nm = "Arrr"
println(s"my name is , $nm")
Is this possible in nim, and in that case, how?
The strfmt module features some experimental string interpolation:
import strfmt
let nm = "Arrr"
echo interp"my name is $nm"
Adding your own string interpolation is not particularly had, since the standard library already provides most of the necessary pieces:
import macros, parseutils, sequtils
macro i(text: string{lit}): expr =
var nodes: seq[PNimrodNode] = #[]
# Parse string literal into "stuff".
for k, v in text.strVal.interpolatedFragments:
if k == ikStr or k == ikDollar:
nodes.add(newLit(v))
else:
nodes.add(parseExpr("$(" & v & ")"))
# Fold individual nodes into a statement list.
result = newNimNode(nnkStmtList).add(
foldr(nodes, a.infix("&", b)))
const
multiplier = 3
message = i"$multiplier times 2.5 is ${multiplier * 2.5}"
echo message
# --> 3 times 2.5 is 7.5
proc blurb(a: int): string =
result = i"param a ($a) is not a constant"
when isMainModule:
for f in 1..10:
echo f.blurb
The strformat module is now considered the go-to way to do it:
import strformat
let nm = "Arrr"
echo fmt"my name is , {nm}"

MATLAB generate combination from a string

I've a string like this "FBECGHD" and i need to use MATLAB and generate all the required possible permutations? In there a specific MATLAB function that does this task or should I define a custom MATLAB function that perform this task?
Use the perms function. A string in matlab is a list of characters, so it will permute them:
A = 'FBECGHD';
perms(A)
You can also store the output (e.g. P = perms(A)), and, if A is an N-character string, P is a N!-by-N array, where each row corresponds to a permutation.
If you are interested in unique permutations, you can use:
unique(perms(A), 'rows')
to remove duplicates (otherwise something like 'ABB' would give 6 results, instead of the 3 that you might expect).
As Richante answered, P = perms(A) is very handy for this. You may also notice that P is of type char and it's not convenient to subset/select individual permutation. Below worked for me:
str = 'FBECGHD';
A = perms(str);
B = cellstr(reshape(A,7,[])');
C = unique(B);
It also appears that unique(A, 'rows') is not removing duplicate values:
>> A=[11, 11];
>> unique(A, 'rows')
ans =
11 11
However, unique(A) would:
>> unique(A)
ans =
11
I am not a matlab pro by any means and I didn't investigate this exhaustively but at least in some cases it appears that reshape is not what you want. Notice that below gives 999 and 191 as permutations of 199 which isn't true. The reshape function as written appears to operate "column-wise" on A:
>> str = '199';
A = perms(str);
B = cellstr(reshape(A,3,[])');
C = unique(B);
>> C
C =
'191'
'199'
'911'
'919'
'999'
Below does not produce 999 or 191:
B = {};
index = 1;
while true
try
substring = A(index,:);
B{index}=substring;
index = index + 1;
catch
break
end
end
C = unique(B)
C =
'199' '919' '991'

Resources