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")
Related
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
I add different Values to the Houdini Variables with Python.
Some of these Variables are file pathes and end with an "/" - others are just names and do not end with an "/".
In my current code I use [:-1] to remove the last character of the filepath, so I dont have the "/".
The problem is, that if I add a Value like "Var_ABC", the result will be "Var_AB" since it also removes the last character.
How can i remove the last character only if the last character is a "/"?
Thats what I have and it works so far:
def set_vars():
count = hou.evalParm('vars_names')
user_name = hou.evalParm('user_name')
for idx in range( 1,count+1):
output = hou.evalParm('vars_' + str(idx))
vars_path_out = hou.evalParm('vars_path_' + str(idx))
vars_path = vars_path_out[:-1]
hou.hscript("setenv -g " + output + "=" + vars_path)
final_vars = hou.hscript("setenv -g " + output + "=" + vars_path)
hou.ui.displayMessage(user_name +", " + "all variables are set.")
Thank you
As #jasonharper mentioned in the comments, you should probably use rstrip here. It is built-in and IMO more readable than the contitional one-liner:
vars_path_out.rstrip('/')
This will strip out those strings which end with / and return without that ending. Otherwise it will return your string as-is.
Try this in your code:
vars_path_out = hou.evalParm('vars_path_' + str(idx))
if vars_path_out[-1] == '/':
vars_path = vars_path_out[:-1]
or
based on the comment of jasonharper
vars_path = vars_path_out.rstrip('/')
This is much better than the first
Use endswith method to check if it ends with /
if vars_path_out.endswith('/')
Or simply check the last character:
if vars_path_out[-1] == '/'
Like this:
vars_path = vars_path_out[:-1] if vars_path_out.endswith('/') else vars_path_out
Or like this:
if vars_path_out.endswith('\'):
vars_path = vars_path_out[:-1]
else:
vars_path = vars_path_out
another way is rstrip method:
vars_path = vars_path_out.rstrip('/')
I'm trying to parse a string which contains several quoted values. Here is what I have so far:
from pyparsing import Word, Literal, printables
package_line = "package: name='com.sec.android.app.camera.shootingmode.dual' versionCode='6' versionName='1.003' platformBuildVersionName='5.0.1-1624448'"
package_name = Word(printables)("name")
versionCode = Word(printables)("versionCode")
versionName = Word(printables)("versionName")
platformBuildVersionName = Word(printables)("platformBuildVersionName")
expression = Literal("package:") + "name=" + package_name + "versionCode=" + versionCode \
+ "versionName=" + versionName + "platformBuildVersionName=" + platformBuildVersionName
tokens = expression.parseString(package_line)
print tokens['name']
print tokens['versionCode']
print tokens['versionName']
print tokens['platformBuildVersionName']
which prints
'com.sec.android.app.camera.shootingmode.dual'
'6'
'1.003'
'5.0.1-1624448'
Note that all the extracted tokens are contains within single quotes. I would like to remove these, and it seems like the QuotedString object is meant for this purpose. However, I'm having difficulty adapting this snippet to use QuotedStrings; in particular, their constructor doesn't seem to take printables.
How might I go about removing the single quotes?
Replacing the expressions with the following:
package_name = QuotedString(quoteChar="'")("name")
versionCode = QuotedString(quoteChar="'")("versionCode")
versionName = QuotedString(quoteChar="'")("versionName")
platformBuildVersionName = QuotedString(quoteChar="'")("platformBuildVersionName")
seems to work. Now the script prints the output
com.sec.android.app.camera.shootingmode.dual
6
1.003
5.0.1-1624448
without quotation marks.
I am trying to append % in a string using string formats.
I am trying to get the below output:
a : [" name like '%FTa0213' "]
Try 1 :
a = [ ]
b = {'by_name':"FTa0213"}
a.append(" name like "%" %s' " %b['by_name'])
print "a :",a
Error :
a.append(" name like "%" %s' " %b['by_name'])
TypeError: not all arguments converted during string formatting
Try 2:
a = [ ]
b = {'by_name':"FTa0213"}
c = "%"
a.append(" name like '{0}{1}' ".format(c,b['by_name'])
print "a :",a
Error :
print "a :",a
^
SyntaxError: invalid syntax
How do I include a % in my formatted string?
To include a percent % into a string which will be used for a printf style string format, simply escape the % by including a double percent %%
a = []
b = {'by_name': "FTa0213"}
a.append(" name like %%%s' " % b['by_name'])
print "a :", a
(Docs)
In your first try, the way you use "%" is wrong; the code below could work for your first try.
a.append( "name like %%%s" % b['by_name'])
Since the "%" is special in python string, so you need to add a "%" before the real "%" to escape.
In your second try, there is nothing wrong in your print, you forgot a ")" in your a.append line. ;-)
just put the % there, no need to set the variable
a = [ ]
b = {'by_name':"FTa0213"}
a.append(" name like '%{}' ".format(b['by_name']))
print "a :",a
the output is
a : [" name like '%FTa0213' "]
You can escape the percent sign by doubling it.
a = []
b = {'by_name': "FTa0213"}
a.append(" name like '%%%s' " % b['by_name'])
print "a :", a
output
a : [" name like '%FTa0213' "]
However, I think it's clearer to use the format method:
a = [ ]
b = {'by_name': "FTa0213"}
a.append(" name like '%{by_name}' ".format(**b))
print "a :", a
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^