Hi I'm new to using html and python. But I need to use html and python interchangeably.
For example,
if python output = 30302,
then I need to put '30302' in the hyperlink.
www.google.com/< output> = www.google.com/30302
html = 'www.google.com/'
python = < output>
how would I combine those two?
The problem
I guess that you wanna create a new string from two parts, i.e. you have a string "www.google.com/" and a variable output with integer 30302 and you wanna get the "www.google.com/30302" (for the future, always provide full examples of your code).
So how can you do it?
Convert int to str and concatenate strs
result = "www.google.com/" + str(output)
str(x) will turn x into a string
Formatting
"www.google.com/{}".format(31415)" is equivalent to the "www.google.com/31415" string,
so result = "www.google.com/{}".format(output)" also will work
in python 3 we also have f-stings:
f"www.google.com/{31415}" == "www.google.com/31415"
result = f"www.google.com/{output}"
Related
i am trying to add some file operation capabilities to a example program, i am strugling with the reading from the file. here is the code that is modified.
def read(fn):
fileout=open(f"{fn}","a+")
fileout.seek(0,0)
s=fileout.readlines()
if s==[]:
print("the file specified does not appear to exists or is empty. if the file does not exist, it will be created")
else:
last=s[-1]
print(last)
print(type(last))
convert(last)
def find(last):
tup=last.partition(".")
fi=tup[0:1]
return fi[0]
def convert(last):
tup=last.partition(".")
part=tup[2:]
print(part)
part=part[0]
print(part)
part=part.split("\n")
print(part)
part=part[0]
print(part)
print(type(part))
#__main__
file(fn)
the write functionality writes in the form of
(fileindex number).[(planned campaign)][(conducted campaign)]
example:- some random data writen to the file by the program(first two number are dates)
0.['12hell']['12hh']
1.['12hell']['12hh']
2.['121341']['132324']
but i am strugling to write the read function, i don't understand how i could convert the data back.
with the current read function i get back
['121341']['132324']
as a string type, i have brainstormed many ideas but could not figureout how to convert string to list(they need to be 2 separate lists)
edit: the flaw as actually in the format that i was writing in, i added a , between the two lists and used eval as suggested in an answer, thanks
Insert a ',' inbetween the brackets, then use eval. This will return a tuple of lists.
strLists = "['121341']['132324']['abcdf']"
strLists = strLists.replace('][', '],[')
evalLists = eval(strLists)
for each in evalLists:
print(each)
Output:
['121341']
['132324']
['abcdf']
I tried below code but it gave
TypeError: string indices must be integers
from nsepython import *
import pandas as pd
import json
positions = nse_optionchain_scrapper ('HDFC')
json_decode = json.dumps(positions,indent = 4, sort_keys=True,separators =(". ", " = "))
print(json_decode['data'][0]['identifier'])
print(json_decode['filtered']['data'][0]['PE']['identifier'])
json_decode = json.dumps(positions,indent = 4, sort_keys=True,separators =(". ", " = "))
You can't build a JSON string (which is what json.dumps does) and then try to access part of the result as if it were the original data structure. Your json_decode is just a string, not a dict; as far as Python is concerned it has no structure beyond the individual characters that make it up.
If you want to access parts of the data, just use positions directly:
print(positions['data'][0]['identifier'])
You can encode just that bit to JSON if you like:
print(json.dumps(positions['data'][0]['identifier'])
but that's probably just a quoted string in this case.
So I'm not sure what your goal is. If you want to print out the JSON version of positions, great, just print it out. But the JSON form is for input and output only; it's not suitable for messing around with inside your Python code.
I need to convert French formatted numbers extracted from .csv into English formatted numbers so I can use dataframe functions. The .csv gives:
Beta Alpha
2014-07-31 100 100
2014-08-01 99,55 100,01336806
2014-08-04 99,33 100,05348297
2014-08-05 99,63 100,06685818
2014-08-06 98,91 100,08023518
"99,5" & "100,01336806" are actually objects for python.
I need to turn them into floats with the following format "99.5" and "100.01336806"
I tried:
df = df.str.replace(to_replace =',', value = '.', case = False)
Doesn't give my any error for that code line but doesn't switch the ',' into '.' either.
df = pd.to_numeric(df, error = 'coerce')
TypeError: arg must be a list, tuple, 1-d array, or Series
Also tried the regex module without success, and I would rather use built-in function if possible.
Any help welcome!
What is the type of sources objects are "99,5" & "100,01336806", and what type of target objects do you want ?
The following tested with Python 3.8
Case 1: source object is numeric, target is string. Formatting do not allow "French format", only "English". So have to substitute . and ,
Eg. (float) 99.55 -> (string) '99,55'
v1 = float(99.55)
f"{v1:,.2f}"
'99.55'
f"{v1:,.2f}".replace(".",",")
'99,55'
Case 2: source is string with "English" format, target is float. Means the , must be replaced by a . first before converting the string to float
Eg. (string) '99,55' -> (float) 99.55
v2 = "99,55"
float(v2.replace(",","."))
99.55
try using the replace() function.
x = "100,01336806"
y = x.replace(",",".")
print(y)
I am using a new script (a) to extract information from an old script (b) to create a new file (c). I am looking for an equal sign in the old script (b) and want to modify the modification script (a) to make it automated.
The string is
lev1tolev2 'from=e119-b3331l1 mappars="simp:180" targ=enceladus.bi.def.3 km=0.6 lat=(-71.5,90) lon=(220,360)'
It is written in python 3.
The current output is fixed at
cam2map from=e119-b3331l1 to=rsmap-x map=enc.Ink.map pixres=mpp defaultrange=MAP res=300 minlat=-71.5 maxlat=90 minlon=220 maxlon=360
Currently, I have the code able to export a string of 0.6 for all of the iterations of lev1tolev2, but each one of these is going to be different.
cam2map = Call("cam2map")
cam2map.kwargs["from"] = old_lev1tolev2.kwargs["from"]
cam2map.kwargs["to"] = "rsmap-x"
cam2map.kwargs["map"] = "enc.Ink.map"
cam2map.kwargs["pixres"] = "mpp"
cam2map.kwargs["defaultrange"] = "MAP"
**cam2map.kwargs["res"] = float((old_lev1tolev2.kwargs["km"]))**
cam2map.kwargs["minlat"] = lat[0]
cam2map.kwargs["maxlat"] = lat[1]
cam2map.kwargs["minlon"] = lon[0]
cam2map.kwargs["maxlon"] = lon[1]
I have two questions, why is this not converting the string to a float? And, why is this not iterating over all of the lev1tolev2 commands as everything else in the code does?
The full code is available here.
https://codeshare.io/G6drmk
The problem occurred at a different location in the code.
def escape_kw_value(value):
if not isinstance(value, str):
return value
elif (value.startswith(('"', "'")) and value.endswith(('"', "'"))):
return value
# TODO escape the quote with \" or \'
#if value.startswith(('"', "'")) or value.endswith(('"', "'")):
# return value
if " " in value:
value = '"{}"'.format(value)
return value
it doesn't seem to clear to me, but from you syntax here :
**cam2map.kwargs["res"] = float((old_lev1tolev2.kwargs["km"]))**
I'd bet that cam2map.kwargs["res"] is a dict, and you thought that it would convert every values in the dict, using the ** syntax. The float built-in should then be called in a loop over the elements of the dict, or possible a list-comprehension as here :
cam2map.kwargs["res"] = dict()
for key, value in old_lev1tolev2.kwars["res"].items():
cam2map.kwargs["res"][key] = float(value)
Edit :
Ok so, it seems you took the string 'from=e119-b3331l1 mappars="simp:180" targ=enceladus.bi.def.3 km=0.6 lat=(-71.5,90) lon=(220,360)'
And then thought that calling youstring.kwargs would give you a dict, but it won't, you can probably parse it to a dict first, using some lib, or, you use mystring.split('=') and then work your way to a dict first, like that:
output = dict()
for one_bit in lev_1_lev2.split(' '):
key, value = one_bit.split('=')
output[key] = value
I'm trying to extract a delimitedString as a list using PyParsing as follows:
from pyparsing import *
string = "arm + mips + x86"
pattern = delimitedList(Word(printables), delim="+")("architectures")
result = pattern.parseString(string)
print(dict(result))
The problem is that this prints
{'architectures': (['arm', 'mips', 'x86'], {})}
which is the string representation of a ParseResult. However, I would like the result to be a Python list:
{'architectures': ['arm', 'mips', 'x86']}
I've looked into doing this with setParseAction, but I wasn't able to figure out how to achieve this using the API of that method. I would actually like to apply list() to the entire ParseResult, but the setParseAction functions have to have the original string, locations, and tokens as input (cf. http://pyparsing.wikispaces.com/HowToUsePyparsing).
How can I post-process the result to make it a list?
Converting to an answer PaulMcG's comment, result.asDict() yields the desired result.