I have question here:
How do I compare variable that has string+decimal in Python.
Example :
a = "2.11.22-abc-def-ghi"
if a == (2.11*) :
print "ok"
I want it only compare the first 2 decimal point only and it doesn't care the rest of it value. How can I do that?
Thanks
Here's the most direct answer to your question, I think...a way to code what your pseudocode is getting at:
a = "2.11.22-abc-def-ghi"
if a.startswith("2.11"):
print("ok")
If you want to grab the numeric value off the front, turn it into a true number, and use that in a comparison, no matter what the specific value, you could do this:
import re
a = "2.11.22-abc-def-ghi"
m = re.match(r"(\d+\.\d+).*", a)
if m:
f = float(m.group(1))
if (f == 2.11):
print("ok")
If you want to compare part of a string, you can always slice it with the syntax str[start_index: end_index] and then compare the slice. Please note the start_index is inclusive and end_index is exclusive. For example
name = "Eric Johnson"
name[0:3] #value of the slice is "Eri" no "Eric".
in your case, you can do
if a[0:4] == "2.11":
#stuff next
Related
I'm not sure I understand what they're asking me to do here, so this is my attempt at doing it.
a='Swim'
b='Run'
if a!=b:
my_boolean = a!=b
print (my_boolean)
the excercise is only asking you to save the value of 'a!=b' in a variable.
However this should help you to understand the code better; you should save 'a != b' only once and then use 'my_boolean' every time you need it, but your code only prints true, because if 'my_boolean' is false, try this:
a = 'Swim'
b = 'Run'
my_boolean = a != b
print(my_boolean)
if my_boolean:
print('printing result: ' + str(my_boolean))
Let's get through it one-by-one. You are trying to compare two strings. If they are exactly the same you should get True otherwise you get False. Doing so would result in a Boolean or bool value.
So, your solution is inverted. It is expected to be:
a='Swim'
b='Run'
my_boolean = (a==b) # This value is boolean already. You can remove the brackets too. I put them for clarity
print (str(my_boolean)) # It works without saying str(), but I did that to show you that the value is converted from the type `bool` into the type String `str`.
Consider the following string:
payments = 'cash:yes,square_cash:no,venmo:no'
If "cash:yes" is found in the string, I would like to return "cash." If "square_cash:yes" is found in the string, I'd like to return "Square Cash" and so on.
I think I'm close, but can't quite figure it out. Here's my code:
payments = 'cash:yes,square_cash:no,venmo:no'
def get_payment_type(x):
return {
x.find('cash:yes') !=-1: 'Cash',
x.find('square_cash:yes') !=-1: 'Square Cash',
x.find('venmo:yes') !=-1: 'Venmo'
}.get(x, 'not found') # default if x not found
return {'payment_used': get_payment_type(payments) }
This always returns "not found", so I know my syntax is off, just not sure where.
Your specific error here is reversing the dictionary keys and values.
dict.get looks up a key and the key is first in the dict syntax:
{"key": "value"}
So if you reverse the keys and values in your answer, it could work.
However, I would recommend a number of changes:
Use if/else and return instead of trying to be clever with dicts. Much easier to read
use x in y instead of y.find(x) != -1
instead of matching strings, a more robust, nicer and more general method is parsing the string into a dictionary.
Here is an example using if, else instead:
if "square_cash:yes" in payments:
return "square_cash"
elif "cash:yes" in payments:
return "Cash"
elif "venmo:yes" in payments:
return "Venmo"
else:
return "not found"
Here is a quick sketch of how parsing this into a dictionary could look:
result = {}
for element in payments.split(","):
key, value = element.split(":")
result[key] = value
To handle arbitrary input, use regex to capture the desired payment type and then if the type exists in the full payment string, capitalize the parts found by re.findall:
import re
payment_types = {'cash:yes,square_cash:no,venmo:no':"cash:yes", 'cash:yes,square_cash:yes,venmo:no':"square_cash:yes"}
final_type = {a:' '.join(i.capitalize() for i in re.findall('^[a-zA-Z_]+(?=:)', b)[0].split('_')) if b in a else None for a, b in payment_types.items()}
Output:
{'cash:yes,square_cash:yes,venmo:no': 'Square Cash', 'cash:yes,square_cash:no,venmo:no': 'Cash'}
Split the string by comma and then use you can use in to check if string is list.
Ex:
payments = 'cash:no,square_cash:yes,venmo:no'.split(",")
if "cash:yes" in payments:
print('Cash')
elif "square_cash:yes" in payments:
print("square_cash")
elif "venmo:yes" in payments:
print("Venmo")
else:
print("not found")
I'm trying to create a "translator" of sorts, in which if the raw_input has any curses (pre-determined, I list maybe 6 test ones), the function will output a string with the curse as ****.
This is my code below:
def censor(sequence):
curse = ('badword1', 'badword2', 'badword3', 'badword4', 'badword5', 'badword6')
nsequence = sequence.split()
aword = ''
bsequence = []
for x in range(0, len(nsequence)):
if nsequence[x] != curse:
bsequence.append(nsequence[x])
else:
bsequence.append('*' * (len(x)))
latest = ''.join(bsequence)
return bsequence
if __name__ == "__main__":
print(censor(raw_input("Your sentence here: ")))
A simple approach is to simply use Python's native string method: str.replace
def censor(string):
curses = ('badword1', 'badword2', 'badword3', 'badword4', 'badword5', 'badword6')
for curse in curses:
string = string.replace(curse, '*' * len(curse))
return string
To improve efficiency, you could try to compile the list of curses into a regular expression and then do a single replacement operation.
Python Documentation
First, there's no need to iterate over element indices here. Python allows you to iterate over the elements themselves, which is ideal for this case.
Second, you are checking whether each of those words in the given sentence is equal to the entire tuple of potential bad words. You want to check whether each word is in that tuple (a set would be better).
Third, you are mixing up indices and elements when you do len(x) - that assumes that x is the word itself, but it is actually the index, as you use elsewhere.
Fourth, you are joining the sequence within the loop, and on the empty string. You should join it on a space, and only after you've checked each element.
def censor(sequence):
curse = {'badword1', 'badword2', 'badword3', 'badword4', 'badword5', 'badword6'}
nsequence = sequence.split()
bsequence = []
for x in nsequence:
if x not in curse:
bsequence.append(x)
else:
bsequence.append('*' * (len(x)))
return ' '.join(bsequence)
Let's say i have a this button:
tl.config(bd=0 ,image=photo1 ,width="100",height="100",command=lambda: functionPlus(tl))
The function is :
def functionPlus(button):
global turn
if (turn==1 or turn==3 or turn==5 or turn==7 or turn==9):
button.config(image=photo2,width="100",height="100")
turn +=1
elif (turn==2 or turn==4 or turn==6 or turn==8) :
button.config(image=photo3,width="100",height="100")
turn+=1
I would like to add an 'if' in the function, that would have as condition the image of the button. For exemple :
if button.config(image=photo2 == True) :
anotherFunction()
Thanks in advance.
First, never use the expression pattern something=something else == True!
Second, take a look at this related (but not duplicate) question.
As you can see there, the cget method will return the current value for an option. As this manual page mentions, cget is analogous to widget["option"].
So, to answer your question directly, the if condition you need would be along the lines of:
if button['image']==photo2:
anotherFunction()
I'm new here and couldn't comment. I hope I'm not flaunting SO policy by resorting to answering instead.
#Tersosauros
"First, never use the expression pattern something=something else ==
True!"
Where do you see this pattern and why should it be avoided? What could replace it? (I know you're a tersosaurus but "never use X" just seems TOO terse and uninformative).
#Arwan Credoz I know you got your answer but... If you simply want to check whether the value of "turn" is a an even/odd number and is within a given range, use a bounds check followed by modulus instead (maybe this is what #Tersosauros was hinting at?).
Also, the value of "turn" will always be incremented if it's within range(0,10) so there's no need to write "turn+=1" twice. If I've understood your intentions correctly, you could probably rewrite "functionPlus" to something like this and add Tersosaurus' addition where appropriate:
def functionPlus(button):
global turn
if 0 < turn < 10:
if turn % 2 == 0:
button.config(image=photo3,width="100",height="100")
else:
button.config(image=photo2,width="100",height="100")
turn += 1
I am fairly new at python (and programming in general, just started 2 months ago). I have been tasked with creating a program that takes a users starting string (i.e. "11001100") and prints each generation based off a set of rules. It then stops when it repeats the users starting string. However, I am clueless as to where to even begin. I vaguely understand the concept of cellular automata and therefore am at a loss as to how to implement it into a script.
Ideally, it would take the users input string "11001100" (gen0) and looks at the rule set I created and converts it so "11001100" would be "00110011" (gen1) and then converts it again to (gen3) and again to (gen4) until it is back to the original input the user provided (gen0). My rule set is below:
print("What is your starting string?")
SS = input()
gen = [SS]
while 1:
for i in range(len(SS)):
if gen[-1] in gen[:-2]:
break
for g in gen:
print(g)
newstate = {
#this is used to convert the string. we break up the users string into threes. i.e if user enters 11001100, we start with the left most digit "1" and look at its neighbors (x-1 and x+1) or in this case "0" and "1". Using these three numbers we compare it to the chart below:
'000': 1 ,
'001': 1 ,
'010': 0 ,
'011': 0 ,
'100': 1 ,
'101': 1 ,
'110': 0 ,
'111': 0 ,
}
I would greatly appreciate any help or further explanation/dummy proof explanation of how to get this working.
Assuming that newstate is a valid dict where the key/value pairs correspond with your state replacement (if you want 100 to convert to 011, newstate would have newstate['100'] == '011'), you can do list comprehensions on split strings:
changed = ''.join(newstate[c] for c in prev)
where prev is your previous state string. IE:
>>> newstate = {'1':'0','0':'1'}
>>> ''.join(newstate[c] for c in '0100101')
'1011010'
you can then use this list comp to change a string itself by calling itself in the list comprehension:
>>> changed = '1010101'
>>> changed = ''.join(newstate[c] for c in changed)
>>> changed
'0101010'
you have the basic flow down in your original code, you jsut need to refine it. The psuedo code would look something like:
newstate = dict with key\value mapping pairs
original = input
changed = original->after changing
while changed != original:
changed = changed->after changing
print changed
The easiest way to do this would be with the re.sub() method in the python regex module, re.
import re
def replace_rule(string, new, pattern):
return re.sub(pattern, new, string)
def replace_example(string):
pattern = r"100"
replace_with = "1"
return re.sub(pattern, replace_with, string)
replace_example("1009")
=> '19'
replace_example("1009100")
=> '191'
Regex is a way to match strings to certain regular patterns, and do certain operations on them, like sub, which finds and replaces patterns in strings. Here is a link: https://docs.python.org/3/library/re.html