Use code tag.
msg=box.content(id[0]) # <-- how will i be able to copy this sms file to a string
print type(msg) #Show what datatype msg is
print msg #Try to print the message
Post the outcome of this
Use code tag.
msg=box.content(id[0]) # <-- how will i be able to copy this sms file to a string
print type(msg) #Show what datatype msg is
print msg #Try to print the message
Post the outcome of this
ip = str(DEVICE_IP) .spilt('.')
.
Spelling error.
ip = str(DEVICE_IP).split('.')
Alternative print line.
print '%s-%s-%s-%s' % (ip[0],ip[1],ip[2],ip[3])
Ok here you go,read a little more about dictionary an basic stuff;)
pairs =\
{"Jeremy": "Jerome",
"Jason": "Fred",
"Joe" : "Fred",
"Alayna" : "Tom",
"Jay" : "Jerome",
"April" : "Tom"}
def find_father():
print "\n This is your current list \n\n", pairs.keys() #We print only sons name
choice_name = raw_input("Please enter a Name: ")
if choice_name in pairs:
print 'Father of %s is %s ' % (choice_name, pairs[choice_name])
else:
print 'Name not in database'
raw_input("\nTrykk enter for meny\n")
def main():
'''Main menu and info '''
while True:
print 'Father finder'
print '(1) Find a Father'
print '(q) Quit'
choice = raw_input('Enter your choice: ')
if choice == '1':
find_father()
elif choice == 'q':
return
else:
print 'Not a correct choice:', choice
if __name__ == '__main__':
main()
Hint.
>>> choice_name = 'Jay'
>>> if choice_name in pairs:
... print 'Father name is %s' % pairs[choice_name]
...
Father name is Jerome
>>>
Use code tag next time,not quote tags.
Look at this code ande try to write the rest(if-else)
pairs =\
{"Jeremy": "Jerome",
"Jason": "Fred",
"Joe" : "Fred",
"Alayna" : "Tom",
"Jay" : "Jerome",
"April" : "Tom"}
def find_father():
print "\n This is your current list \n\n", pairs.keys() #We print only sons names
pass
def main():
'''Main menu and info '''
while True:
print 'Father finder'
print '(1) 1 - Find a Father'
print '(q) Quit'
choice = raw_input('Enter your choice: ')
if choice == '1':
find_father()
elif choice == 'q':
return
else:
print 'Not a correct choice:', choice
if __name__ == '__main__':
main()
Is python web programming anything like php?
Yes you have python CGI programming.
A commen task in php is getting data from a HTML form.
Here is an example in python.
http://webpython.codepoint.net/cgi_unique_field_names
CGI is run from server side,so you can say it`s a sever side like php but you write in python.
So if you want to test it out use local server like xampp/wamp.
So there is possible to make a html form calulator and let python do calculations.
A more commen way is like postet over,to use a python web-framework.
that has nothing to do with it
Yes,i know it was just a tip.
Read this then you understand why you should use \\ or / in windows.
Never only \ in a path to a file in windows with python.
http://pythonconquerstheuniverse.wordpress.com/2008/06/04/gotcha-%E2%80%94-backslashes-are-escape-characters/
File "C:\Users
Use "File "C:\\Users" or C:/Users
A little verbose but see if it can help you.
import re
txt = '2008/03/25 log:true lcp: 78888 -> 100 lck=0 to=900 un=5840 l=0 BMN'
re1 = '.*?' # Non-greedy match on filler
re2 = '(lcp)' # Word 1
re3 = '(:)' # Any Single Character 1
re4 = '(\\s+)' # White Space 1
re5 = '(\\d)' # Any Single Digit 1
re6 = '(\\d)' # Any Single Digit 2
re7 = '(\\d)' # Any Single Digit 3
re8 = '(\\d)' # Any Single Digit 4
re9 = '.*?' # Non-greedy match on filler
re10 = '(?:[a-z][a-z]+)' # Uninteresting: word
re11 = '.*?' # Non-greedy match on filler
re12 = '(?:[a-z][a-z]+)' # Uninteresting: word
re13 = '.*?' # Non-greedy match on filler
re14 = '(?:[a-z][a-z]+)' # Uninteresting: word
re15 = '.*?' # Non-greedy match on filler
re16 = '((?:[a-z][a-z]+))' # Word 2
rg = re.compile(re1+re2+re3+re4+re5+re6+re7+re8+re9+re10+re11+re12+re13+re14+re15+re16,re.IGNORECASE|re.DOTALL)
m = rg.search(txt)
if m:
word1 = m.group(1)
c1 = m.group(2)
ws1 = m.group(3)
d1 = m.group(4)
d2 = m.group(5)
d3 = m.group(6)
d4 = m.group(7)
word2 = m.group(8)
w = word1 + c1 + ws1 + d1 + d2 + d3 + d4 + word2
print w #lcp: 7888BMN
Somthing like this,i make a mark_check() function.
Use exception handling to catch wrong input.
Not much wrong with you code just test the if-elif-else condition to get the result you want.
def calcFinal():
while True:
try:
asg1Mark = int(raw_input("Enter Asg1 mark: "))
asg2Mark = int(raw_input("Enter Asg2 mark: "))
examMark = int(raw_input("Enter Exam mark: "))
final = asg1Mark + asg2Mark + examMark
return final
except ValueError:
print 'Only numbers,try again'
def mark_check(finalMark):
print "Final mark is %d, grade is" % finalMark,
if finalMark < 50:
print "Fail"
elif finalMark <= 65:
print "Pass"
elif finalMark <= 75:
print "credit"
elif finalMark <= 85:
print "Distinction"
elif finalMark >= 85:
print "High Distinction"
else:
print "Invaild selction"
def main():
finalMark = calcFinal()
mark_check(finalMark)
if __name__ == "__main__":
main()
Change the code with and try-except block,so it dont crash when letter is the input.
def dec():
while True:
try:
x = float(raw_input('enter number: '))
if x % 1 == 0:
print ("The number entered must be a decimal number")
else:
return x
except ValueError:
print 'Numer only'
dec()
The code it is not tested, but should be worked
You should test it because it is not working:-/
Here you have one way off do it.
This is for python 3 that i think you use.
Homework?,they may spot that you havent wirte this code(some smart shortcut in this code)
You may work on the for loop you startet with(now your code is not working)
def makeList():
num = input('Please enter the number of strings you want to input\n')
alist = []
for i in range(int(num)):
x = input('Enter string please: ')
alist.append(x)
return sorted(alist)
def findShortest(alist):
min_list = min(alist, key=len)
return (min_list)
def findLongest(alist):
max_list = max(alist, key=len)
return max_list
def findAlpha(alist):
alpha_list = [item for item in alist if str(item).isalpha()]
return alpha_list
def main():
alist = makeList()
print ('Sorted list is:\n{0}'.format(alist))
print ('Shortest element is:\n{0}'.format(findShortest(alist)))
print ('Longest element is:\n{0}'.format(findLongest(alist)))
print ('Only alphabetic characters is:\n{0}'.format(findAlpha(alist)))
if __name__ == "__main__":
main()
'''Out-->
Sorted list is:
['car', 'taxi', 'train5']
Shortest element is:
car
Longest element is:
train5
Only alphabetic characters is:
['car', 'taxi']
'''
A good start with wxpython.
http://www.youtube.com/watch?v=RHvhfjVpSdE
And off course on this site.
http://www.daniweb.com/forums/thread128350.html
Tkinter has an native an rather ugly look on windows.
Use another tool kit like wxpython(my favorite) or PyQt.
They look good on windows and have more lot option for creating good looking GUI.
I was wondering if there are any GUI toolkits in python that create native-looking windows in Windows 7
Wxpython-PyQt dont have the ugly and native-looking that Tkinter has on all windows version.
Tkinter look better on linux,mac.
I postet a wxpython picture here.
http://www.daniweb.com/forums/thread252780.html
Wxpython are a very good gui-toolkit and you have a lot more option than tkinter.
There is no confusion about how my function work.
It will return a correct date format in yyyymmdd an nothing else.
I know regular expression is not easy to learn and can be confusing.
The other way is to check every number with range function or a tuple version.
Look at this post here you see how to check that numbers are correct without regular expression.
http://www.daniweb.com/forums/thread265942.html
You can look a datetime module and see if it have a check for date format.
http://docs.python.org/library/datetime.html
For this regular expression can be to help.
This funtion will only return correct date format in | yyyy-mm-dd | or | yyyy/mm/dd |
import re
def foo():
while True:
print 'use format | yyyy-mm-dd |'
date_input = raw_input("Enter date: ")
if re.match(r"(?:(19|20)[0-9]{2}[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01]))\Z", date_input):
print 'Match'
return date_input
else:
print 'No match,try again'
print foo()
'''-->Out
use format | yyyy-mm-dd |
Enter date: 2000-13-25
No match,try again
use format | yyyy-mm-dd |
Enter date: 2000-12-25
Match
2000-12-25
'''
Yes i have to wait for 3 party libraries to be ported to python 3.x.
Like wxpython very much so have to wait for that to by portet to python 3.x
Have off course python 3.x installed to look at changes.
Twistet i think will not be ported to python 3.x before 2015.
I think there is no problem at all to stay with python 2.x,if project that not need 3 party libaryes then man can use python 3.x
Just a note. "C:\Documents
.
For windows use. "C:\\Documents or "C:/Documents
if i want to delete red data of only key '172.14' all in from array
You can use vega code for this.
mylist = newlist
print(mylist)
So now mylist has removed item you want(garbage collection)old mylist do not exits.
Or an another soultion.
mylist = [
'192.168.255.1 00:01:02',
'172.14.0.1 00:0f:01',
'172.14.0.2 00:0f:01',
'172.14.0.3 00:0f:01'
'172.14.0.4 01:ff:dd:34',
'192.168.255.3 00:dd:01:ff'
]
for item in mylist[:]:
if item.startswith('172'):
mylist.remove(item)
print mylist
You have to see difference between python 2.x and python 3.x
Most off us will use python 2.x for a copule off year til 3 party moduls is rewritten for python 3.x
Here is code for python 3.x
h2 = range (0,4)
m1 = range(0,6)
m2 = range(0,10)
mtime_range = (0,4)
def valid_mtime(mtime):
if len(mtime) not in mtime_range:
print ('Not correct lenght')
return
if (int(mtime[0]) in h1 and int(mtime[1]) in h2) and (int(mtime[2]) in m1 and int(mtime[3]) in m2):
print ('true')
else:
print ('false')
The tuple version from __qwerty__ work also good.
You can rewrite as traning for python 3.x
Use IDLE to break it down if you dont understand.
>>> h
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
>>> mtime = '2350'
>>> mtime
'2350'
>>> mtime[0]
'2'
>>> mtime[1]
'3'
>>> if mtime[0] in h:
print 'true'
>>> if int(mtime[0]) in h:
print 'true'
true
>>> len(mtime)
4
>>> #Here you see one problem in __qwerty__ code have to change to int.
>>> #Read about and/or(not(Boolean Operations) how it work
So a little change to get it to work.
h1 = range(0,3)
h2 = range (0,4)
m1 = range(0,6)
m2 = range(0,10)
mtime_range = (0,4)
def valid_mtime(mtime):
if len(mtime) not in mtime_range:
print 'Not correct lenght'
return
if (int(mtime[0]) in h1 and int(mtime[1]) in h2) and (int(mtime[2]) in m1 and int(mtime[3]) in m2):
print 'true'
else:
print 'false'
'''Out-->
valid_mtime('0059')
true
valid_mtime('0060')
false
valid_mtime('24')
Not correct lenght
'''
Here is a solution with reglular expression you can look at.
import re
def valid_mil_time(mtime):
if re.match(r"(?:([01]\d|2[0-3]):?[0-5]\d)\Z",mtime,re.IGNORECASE):
print ("true")
else:
print ("false")
'''Out-->
valid_mil_time('0059')
true
valid_mil_time('0060')
false
valid_mil_time('2359')
true
valid_mil_time('2459')
false
'''
Though there are advantages to using full IDEs such as netbeans
Vega is not talking about big editors like netbean that support many languages.
Pyscripter,SPE are small python editors that work out the box,just paste in code an run it.
And will give a god error message and where in code if somthing goes wrong.
word1 = 'This is my car'
word2 = 'My car is fine'
diff_list = []
for item in word1:
if not item in word2:
diff_list.append(item)
print diff_list
And for index that i forget we can use vega code with a litte twist.
word1 = 'This is my car'
word2 = 'My car is fine'
diff_list = []
for item in word1:
if not item in word2:
diff_list.append(item)
print diff_list
for letter in diff_list:
index = str(diff_list).find(letter)
print( "letter %s is at index %s" % (letter, index))
'''Out-->
['T', 'h', 'm']
letter T is at index 2
letter h is at index 7
letter m is at index 12
'''
def common_letter():
#word1 = raw_input("Enter word1: ")
#word2 = raw_input("Enter word2: ")
word1 = 'This is my car'
word2 = 'My car is fine'
li1 = []
li2 = []
for letter1 in word1:
li1.append(letter1) #This is better
for letter2 in word2:
li2 += letter2
print li1 #Now you have two list with the word
print li2 #And nothing is compared
diff_list = [item for item in li1 if not item in li2]
#Can write it as a loop if this is hard to understand
print diff_list
common_letter()
redyugi you code dos the same as set()
print len(set(["bread","cookies","cake","chocolate","bread"]))
4
That only remove duplicate in a list.
For count with set() this is a solution.
wordlist = ["bread", "cookies", "cake", "chocolate", "bread"]
for item in set(wordlist):
print '%s %s' % (item,wordlist.count(item))
'''Out-->
cake 1
cookies 1
chocolate 1
bread 2
'''
From a editor is the way most off us do it.
Pyscripter er god for windows.
http://code.google.com/p/pyscripter/
Linux is SPE er bra.
sudo apt-get install spe
For IDLE.
Fil->new window
Write your code and run it(F5)
You need to read a little this to basic,and everyone should at lest figurer this out.
http://www.ibiblio.org/swaroopch/byteofpython/read/source-file.html
http://www.youtube.com/watch?v=4Mf0h3HphEA&feature=SeriesPlayList&p=EA1FEF17E1E5C0DA
>>> num = raw_input("Enter a number: ")
>>> l = []
>>> for item in range(int(num)):
... a = int(raw_input('Enter: '))
... l.append(a)
...
>>> l
[5, 6, 3, 4, 7]
>>>
Always use 4 space for indentations PEP 8
Here is a little help on how to trow more than one dice.
import random
possible = [2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 30, 34, 50, 100]
dice_number = int(raw_input('How many dice would you like to use: '))
size = int(raw_input('Please enter the size of the die you would like: '))
if size not in possible:
print
"""
Please check the Wikipedia Dice article to get possible dice sizes.
I'm going to give you a standard 6 sided die to try out.
"""
size = 6
rolltimes = int(raw_input('Please enter the number of times to roll: '))
dice = [x for x in range(1,size+1)]
rollval = []
dictionary = {}
for count in range(0,rolltimes):
for i in range(0,dice_number):
item = dice[random.randrange(len(dice))]
dictionary[item] = dictionary.get(item,0) + 1
items = dictionary.keys()
items.sort()
for item in items:
print "%-10s %d" % (item, dictionary[item])
To check for a valid email adress regular expression is a god tool.
import re
mail_input = raw_input("Enter your email: ")
if re.match(r"\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b\Z", mail_input, re.IGNORECASE):
print ("That is a valid email")
else:
print ("That email is not valid")
That is making it more difficult than it need to be Tech B.
n = raw_input('enter a number: ')
first_n = int(n[0])
print first_n
I'm an information security professional who's decided to teach myself python
Yes a good choice.
I put together something that may in direction you describe.
import re
text = '''\
A fast and friendly dog.
email1@dot.net
myetest@online.no
My car is red.
han445@net.com
'''
find_email = re.findall(r'\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b',text,re.IGNORECASE)
print 'Text has %d email adress' % (len(find_email))
print find_email
for item in enumerate(find_email):
print 'Email #%s --> %s' % (item[0],item[1])
'''Out-->
Text has 3 email adress
['email1@dot.net', 'myetest@online.no', 'han445@net.com']
Email #0 --> email1@dot.net
Email #1 --> myetest@online.no
Email #2 --> han445@net.com
'''
#Python 3.x
find_email = re.findall(r'\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b',text,re.IGNORECASE)
print ('Text has %d email adresser' % (len(find_email)))
print (find_email)
for item in enumerate(find_email):
print ('Email #%s --> %s' % (item[0],item[1]))
costAd() <-- dead code after the return statement :)
No you dont give function an argument. def costAd(numChar):
Then you most always pass an argument when calling the function.
Your error message is pretty clear.
TypeError: costAd() takes exactly 1 argument (0 given)
Look at vega code. costAd(20)
If we give a default value as argument we can call like this or with an argument
def costAd(numChar=0):
if numChar >= 15:
cost = 35.00
else:
cost = 35.00 + ((numChar - 15) * 3.55)
return cost
print costAd()
print costAd(20)
Hei fra norge.
This is an almost impossible task without a good libary.
I did a translation program a while ago where i use google translate API and wxpython as gui.
Its work fine,still only in norwegian.
Shall write gui fronend in englishs to.
Did this a fun projects.you can try it out Py-trans
import wx
class HorizontalToolbar(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(240, 200))
toolbar = self.CreateToolBar(wx.TB_HORIZONTAL)
toolbar.AddLabelTool(wx.ID_ANY, '', wx.Bitmap('1ico.ico'))
toolbar.AddLabelTool(wx.ID_ANY, '', wx.Bitmap('2ico.ico'))
toolbar.Realize()
self.Centre()
self.Show(True)
def OnExit(self, event):
self.Close()
app = wx.App()
HorizontalToolbar(None, -1, 'horizontal toolbar')
app.MainLoop()
This was very bad,not worth anyone times.
The gui builder for wxpython could be better,but they are much better than this.
It just gave a message at the bottom of the gray PythonWin frame right where it says,"running the code file..." or something similar to that
Get a better editor than PythonWin.
Pyscripter is good.
Paste your kode inn,and you se a red line mark under line 7 for your code.
It also give you and postion(25) if you try to run the code.
Because at postion(25) there should be a :
as Gribouillis pointet out.
You dont need to use ;
in python.
First we breake it down in python IDLE.
IDLE 2.6.4
>>> exp = "1+2"
>>> exp
'1+2'
>>> string1 = exp.split("+")
>>> string1
['1', '2']
>>> print "Operator 1 is : " , op1
Operator 1 is :
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
print "Operator 1 is : " , op1
NameError: name 'op1' is not defined
#just to get and error message "NameError" because we have nor defiend op1.
>>> print "Operator 1 is: %s " % string1[0]
Operator 1 is: 1
So the finish script.
def start():
exp = "1+2"
string1 = exp.split("+")
print "Operator 1 is: %s" % string1[0]
print "Operator 2 is: %s" % string1[1]
start()
'''Out-->
Operator 1 is: 1
Operator 2 is: 2
'''
Post 2# my setup in gui2exe.
I have done a lot with wxpython and py2exe(gui2exe + inno-setup)
And it works on all windows version,no need for pepole to have python installed.
Is better that you post your script so can we test it out.
Post your script so can i test i out.
I think I should listen to your advice and also get python 2, so I'll be able to learn something at all.
Yes both Guido(python himself) and Alex Martelli say that beginner should start with python 2.x.
They have now hurry to advice pepole to use python 3.x,because is newer.
In some year all will use python 3.x but no need to hurry upp,and refuse all code on net that is for python 2.x(for beginner is this code very important and books to)
The easy way is using 5min to install python 2.x.
And see if you get it to work there,if it work rewrite to python 3.x.
The problem is that very few use python3.x yet.
So getting help with python 3.x is much harder than for python 2.x
I have used 2to3 module to port python 2.x to python 3.x code,and it have work fine for the little i have tryed.
For small script i have not much problem to rewrite to python 3.x
oh and I know how to use google btw, maybe even better then you do...
Then you should know that urllib2 has been integrated into urllib in python 3.
http://www.python.org/dev/peps/pep-3108/#urllib-package
http://diveintopython3.org/porting-code-to-python-3-with-2to3.html#urllib
Most of us use python 2.x,because we need 3 party moduls like wxpython,Twisted,dangjo,py2exe...and so on.
No problem to have both python 2.x and python 3.x installed.
Python 3.x is off course the right to go in the future,but for 3 party moduls future is still some years away.
By the way nowone will wirte code for you if you dont show som effort an post what you have done.
You can look at this,for taking out values.
l = []
for i in open('your.txt'):
l.append(i[0:2])
print l
l1 = l[0]
print l1
'''Out-->
['10', '12', '4,']
10
'''
You dont need two //,only if it is this way \\.
So this will work on windows.
os.system("myprog /mydir_where_there_is_xm/myxml.xml")