Python convert set string to set - python

I have a string that looks like
{'dir1/dir2/k8s-dag-model.py', 'dir1/dir2/[updated]airflow-issue.txt', 'dir1/dir2/1.log', 'dir1/dir2/cloud_formation.py', 'dir1/dir2/example_sftp_to_s3.py', 'dir1/dir2/catalog_sales.csv', 'dir1/dir2/dep-dremio0.sh', 'dir1/dir2/store_sales (1).csv', 'dir1/dir2/example_datasync_1.py', 'dir1/dir2/spark-svc.yaml'}
I want to convert it to set how can i do that?
using set(a.split(",")) converting it into
{" 'dir1/dir2/spark-svc.yaml'}", " 'dir1/dir2/store_sales (1).csv'", " 'dir1/dir2/[updated]airflow-issue.txt'", " 'dir1/dir2/dep-dremio0.sh'", " 'dir1/dir2/example_sftp_to_s3.py'", " 'dir1/dir2/catalog_sales.csv'", " 'dir1/dir2/cloud_formation.py'", " 'dir1/dir2/1.log'", "{'dir1/dir2/k8s-dag-model.py'", " 'dir1/dir2/example_datasync_1.py'"}
here I have to remove ' and {,} . Is there a standard way to do it.

You can convert a String to a set/list using literal_eval
import ast
x = "{'dir1/dir2/k8s-dag-model.py', 'dir1/dir2/[updated]airflow-issue.txt', 'dir1/dir2/1.log', 'dir1/dir2/cloud_formation.py', 'dir1/dir2/example_sftp_to_s3.py', 'dir1/dir2/catalog_sales.csv', 'dir1/dir2/dep-dremio0.sh', 'dir1/dir2/store_sales (1).csv', 'dir1/dir2/example_datasync_1.py', 'dir1/dir2/spark-svc.yaml'}"
y = ast.literal_eval(x)
print(y)
Since the same works for a list too a similar answer for a list: https://stackoverflow.com/a/1894296/5236575
Docs: https://docs.python.org/3/library/ast.html#ast.literal_eval

Related

Simple logical syntax termcolor python

I have simple logical problem with my code. I want my console's output is blue so I import termcolor, but this the problem
from termcolor import colored
winner_name = "John"
result = colored((">>",winner_name,"<<"),"blue")
print(result)
when the code executed, the output is
('>>', 'John" , '<<')
I tried some replace funct
results = result.replace( "(" and ")" and "'" , "" )
This work but the output is
(>> , John , <<)
I Want the output is
>> John <<
You're constructing a tuple. You need to make a single string. There are several ways to do so. You could use + directly
">> " + winner_name + " <<"
or, more idiomatically, you can use f-strings.
f">> {winner_name} <<"
It's printing the brackets because you are printing the tuple.
If you are using a newer version of python you can use f strings:
result = colored(f">> {winner_name} <<", "blue")
Otherwise you can do it like this:
result = colored(">>" + winner_name + "<<", "blue")
Use this instead
colored(f">> {winner_name} <<", "blue")
the variable name in curled brackets will be replaced by it's value inside the f string.
If you don't want to use f strings
colored(">>" + winner_name + "<<", "blue")

Format string output

With this python's code I may read all tickers in the tickers.txt file:
fh = open("tickers.txt")
tickers_list = fh.read()
print(tickers_list)
The output that I obtain is this:
A2A.MI, AMP.MI, ATL.MI, AZM.MI, BGN.MI, BMED.MI, BAMI.MI,
Neverthless, I'd like to obtain as ouput a ticker string exactly formatted in this manner:
["A2A.MI", "AMP.MI", "ATL.MI", "AZM.MI", ...]
Any idea?
Thanks in advance.
If you want the output to look in that format you want, you would need to do the following:
tickers_list= "A2A.MI, AMP.MI, ATL.MI, AZM.MI, BGN.MI, BMED.MI, BAMI.MI"
print("["+"".join(['"' + s + '",' for s in tickers_list.split(",")])[:-1]+"]")
With the output:
["A2A.MI"," AMP.MI"," ATL.MI"," AZM.MI"," BGN.MI"," BMED.MI"," BAMI.MI"]
Code explanation:
['"' + s + '",' for s in tickers_list.split(",")]
Creates a list of strings that contain each individual value, with the brackets as well as the comma.
"".join(...)[:-1]
Joins the list of strings into one string, removing the last character which is the extra comma
"["+..+"]"
adds the closing brackets
Another alternative is to simple use:
print(tickers_list.split(","))
However, the output will be slightly different as in:
['A2A.MI', ' AMP.MI', ' ATL.MI', ' AZM.MI', ' BGN.MI', ' BMED.MI', ' BAMI.MI']
Having ' instead of "
A solution for that however is this:
z = str(tickers_list.split(","))
z = z.replace("'",'"')
print(z)
Having the correct output, by replacing that character
you can to use Split function:
tickers_list = fh.read().split(',')

How to concatenate multiple variables?

I have three UV sensors - integers output; one BME280 - float output (temperature and pressure); and one GPS Module - float output.
I need to build a string in this form - #teamname;temperature;pressure;uv_1;uv_2;uv_3;gpscoordinates#
and send them via ser.write at least one time per second- I'm using APC220 Module
Is this the right (and fastest) way to do it?
textstr = str("#" + "teamname" + ";" + str(temperature) + ";" + str(pressure) + ";" + str(uv_1) + ";" + str(uv_2) + ";" + str(uv_3) + "#")
(...)
ser.write(('%s \n'%(textstr)).encode('utf-8'))
You may try something like this:
vars = [teamname, temperature, pressure, uv_1, uv_2, uv_3, gpscoordinates]
joined = ';'.join( map( str, vars ))
ser.write( '#%s# \n', joined )
If using python 3.6+ then you can do this instead
textstr = f"#teamname;{temperature};{pressure};{uv_1};{uv_2};{uv_3}# \n"
(...)
ser.write((textstr).encode('utf-8'))
If teamname and gpscoordinates are also variables then add them the same way
textstr = f"#{teamname};{temperature};{pressure};{uv_1};{uv_2};{uv_3};{gpscoordinates}# \n"
(...)
ser.write((textstr).encode('utf-8'))
For more info about string formatting
https://realpython.com/python-f-strings/
It might improve readability to use python's format:
textstr = "#teamname;{};{};{};{};gpscoordinates#".format(temperature, pressure, uv_1, uv_2, uv_3)
ser.write(('%s \n'%(textstr)).encode('utf-8'))
assuming gpscoordinates is text (it's not in your attempted code). If it's a variable, then replace the text with {} and add it as a param to format.

basic Python JSON Datetime convert issue

i'm a python beginner and having an issue. Trying to pull API info and convert the extracted JSON time object to a datetime object in Python so I can run the date.weekday() function on it eventually (the overall goal is to extract all the dates from the API and see which the output by days - I plan on populating a empty dictionary once I can extract all the dates).
For some reason, even with my conditional statements, I'm still printing (2015, 04, 06) with all the zeroes. That's my problem.
I have a feeling I'm getting something basic wrong, and that there's also a better way to go about this than doing all the ifs/elses with the 0-padding in the date object.
here's my code so far:
from datetime import date
import datetime
import json
import requests
r = requests.get('https://api.github.com/repos/mbostock/d3/commits?since=2015-04-12330:00:000')
jsonoutput = r.json()
modified = (jsonoutput[0]["commit"]["author"]["date"])
#at this point, modified gives something like: "2015-04-06T22:28:16Z"
if modified[5] == 0:
if modified[8] == 0:
new_format = ("(" + modified[0:4] + ", " + modified[6] + ", " + modified[9] + ")")
#with the particular jsonoutput[0] pulled here, this one should be triggered
else:
new_format = ("(" + modified[0:4] + ", " + modified[6] + ", " + modified[8:10] + ")")
else:
if modified[8] == 0:
new_format = ("(" + modified[0:4] + ", " + modified[5:7] + ", " + modified[9] + ")")
else:
new_format = ("(" + modified[0:4] + ", " + modified[5:7] + ", " + modified[8:10] + ")")
print(new_format)
print(date.weekday(datetime.date(new_format)))
The error happens in your current code because new_format is defined as a string, while the datetime.date takes the arguments as integers. Also, since you compare the string "0" with the numerical 0, the modified is simply not created.
Instead of this:
new_format = ("(" + modified[0:4] + ", " + modified[6] + ", " + modified[8:10]) + ")")
do this:
new_format = (int(modified[0:4]), int(modified[5:7]), int(modified[8:10]))
The above will work with all of your cases, so you can remove the convoluted if-else blocks as well.
Alternatively, you could split this modeified string by "T", and then use another split by "-" to get the integer values:
new_format = map(int, modified.split("T")[0].split("-"))
You'll also need to unpack the list when passing as the argument, so your complete code becomes:
import json
import requests
from datetime import date
r = requests.get('https://api.github.com/repos/mbostock/d3/commits?since=2015-04-12330:00:000')
jsonoutput = r.json()
modified = jsonoutput[0]["commit"]["author"]["date"]
new_format = (int(modified[0:4]), int(modified[5:7]), int(modified[8:10]))
print(date.weekday(date(*new_format)))
Also, as others have already pointed out in their answers, it might be a better idea to dateutil.parser.parse than to write your own parsing logic. (dateutil is not a builtin package, you'll have to install it) :)
What you get from the json is actually a datetime representation in an ISO format
You can refer to this SO answer https://stackoverflow.com/a/15228038/58129 to convert the string
You're trying to make your own parsing functions where Python has its own.
from dateutil import parser
from datetime import date
my_date = dateutil.parser.parse(modified)
is_week_day = date.weekday(my_date)
If dateutil is not installed on your machine, try pip install python-dateutil
However, if you want to go with Python's standard library:
from datetime import date, datetime
from time import strptime
mytime = strptime(modified, '%Y-%m-%dT%H:%M:%SZ')
my_date = datetime(*my_time[:6])
is_week_day = date.weekday(my_date)

Writing multiple values in a text file using python

I want to write mulitiple values in a text file using python.
I wrote the following line in my code:
text_file.write("sA" + str(chart_count) + ".Name = " + str(State_name.groups())[2:-3] + "\n")
Note: State_name.groups() is a regex captured word. So it is captured as a tuple and to remove the ( ) brackets from the tuple I have used string slicing.
Now the output comes as:
sA0.Name = GLASS_OPEN
No problem here
But I want the output to be like this:
sA0.Name = 'GLASS_HATCH_OPENED_PROTECTION_FCT'
I want the variable value to be enclosed inside the single quotes.
Does this work for you?
text_file.write("sA" + str(chart_count) + ".Name = '" + str(State_name.groups())[2:-3] + "'\n")
# ^single quote here and here^

Categories