880 Posted Topics
Re: >>> s = 'hi my name is bill' >>> ''.join(s.split()) 'himynameisbill' >>> list(''.join(s.split())) ['h', 'i', 'm', 'y', 'n', 'a', 'm', 'e', 'i', 's', 'b', 'i', 'l', 'l'] | |
![]() | Re: Look at `os.path.exists` and `os.path.isfile` thats dos what you describe. >>> help(os.path.exists) Help on function exists in module genericpath: exists(path) Test whether a path exists. Returns False for broken symbolic links >>> help(os.path.isfile) Help on function isfile in module genericpath: isfile(path) Test whether a path is a regular file Or … ![]() |
Re: > or how would you change it (or may be some part of it) to looks it more elegant and to be more efficient. > > here is the code: > You are making 88 random numbers in range 0 to 9 and want to count occurrence. use randint() because … | |
Re: The tutorial about BeautifulSoup is not so good. The use of regex is not needed,let BeautifulSoup do the job. Regex with html is not so good,you can mix in regex some time to do a little cleaning. But here it`s not needed. To get all picture from this link. from … | |
Re: Using re.split() is also and option. >>> import re >>> s = '1--2--3--4---5---6--7---8' >>> re.split(r'\-+', s) ['1', '2', '3', '4', '5', '6', '7', '8'] | |
Re: itertools.product will also do this. import itertools import pprint letters = ['A', 'B', 'C'] pprint.pprint(list(itertools.product(letters, repeat=3))) """Output--> [('A', 'A', 'A'), ('A', 'A', 'B'), ('A', 'A', 'C'), ('A', 'B', 'A'), ('A', 'B', 'B'), ('A', 'B', 'C'), ('A', 'C', 'A'), ('A', 'C', 'B'), ('A', 'C', 'C'), ('B', 'A', 'A'), ('B', 'A', 'B'), … | |
Re: Use code tag so indentation works. You are doing some unnecessary stuff. The answer is not so long,so i dont break it up. with open('age.txt') as f: for item in f: sorted_list = sorted(item.split(','), key=int) with open('age_out.txt', 'w') as f_out: f_out.write(','.join(sorted_list)) #--> 12, 13, 14, 15, 16, 17, 18, 19, … | |
Re: Or like this. >>> [float(numb[0]) for item in alist for numb in item] [0.77, 0.34, 0.12, 0.0, 0.0, 0.0] If i break up list comprehension up it can be eaiser du understand what`s going on. >>> alist = [[], [(u'0.77',)], [(u'0.34',)], [(u'0.12',)], [(u'0',)], [(u'0.0',)], [(u'0',)]] >>> numb_list = [] >>> … | |
Re: Dont use array,in python we call it `list`. `import array` is only for very specialized task. Your indentation is wrong and you read in file more than once. Take a look at this,and you should read a basic tutorial about list in python. numb_list = [] with open('numb.txt') as f: … | |
Re: > Does first alternative not work in Python 3? No,in python 3 print is a function. Read about diffrence. http://diveintopython3.ep.io/porting-code-to-python-3-with-2to3.html | |
Re: You can try binarie install from this site. http://www.voidspace.org.uk/python/modules.shtml#pycrypto | |
Re: There is no error i code you posted. Post code with Traceback you get. > so python use ## This is the example of the code. and so on like any Yes you can use 1 # or two ##..,to make comments in code. > Now from these two programs … | |
Re: This will do it,run script in same folder as pdf1,pdf2... Output will be project 1, project 2... Be aware that this will rename all pdfs in folder that you run script in. import os import glob for numb, name in enumerate(glob.glob('*pdf'), 1): #print numb, name #test os.rename(name, 'project %s.pdf' % … | |
Re: > Because all I need to do is scan the entire drive (C: as it would be in this case) for any file matching the .xyz extension, and create a list of all found files. In basic something like this. import os file_list = [] for root, dirs, files in … | |
Re: Hmm that type-checking is from outer space. You should not use [ICODE]vars()[/ICODE]. [ICODE]vars()[/ICODE] or [ICODE]locals(),globals()[/ICODE] provides low level access to variables created by python. Dont use python internal working in your code. To check for integer or float here a couple of way. Here you only get out of loop … | |
Where is sticky treads starting python,Gui programming....? These were very good treads and should be sticky. | |
Re: I wonder about the same as woooee. Using a parser can be better for this task as BeautifulSoup or lxml. A quick demo. [CODE]from BeautifulSoup import BeautifulStoneSoup xml = '''\ <tag> <number>1</number> <info>blah blah</info> <more>Lorem Ipsum</more> <anothertag>The quick brown fox...</anothertag> <id>32444</id> <yetmore>blah blah</yetmore> </tag> <tag> <number>2</number> <info>qwerty</info> <more>yada yada qwerty</more> … | |
Re: Code are sending shellcode through a socket with python code. [QUOTE]Shellcode is a piece of machine-readable code, or script code that has just one mission; to open up a command interpreter (shell) on the target system so that an “attacker” can type in commands in the same fashion as a … | |
Re: You have a post with same question. [url]http://www.daniweb.com/software-development/python/threads/416862[/url] In this post you give more info about html file. What you post now is just a mess,read about function. Is this a school task? can you use regex in this task? [CODE]import re info = '''<table> <tr align = "center"> <h1> … | |
Re: [QUOTE]By the way, you may want to look at the BeautifulSoup Python library for working with html files (and extracting text from them). [/QUOTE] I agree with this,but now it look like boiishuvo will destroy the stucture of html. Should it replace like this or keep <> intact? [CODE]>>> s … | |
Re: A little more about this. [ICODE]is[/ICODE] is the identity comparison. [ICODE]==[/ICODE] is the equality comparison. With [ICODE]id()[/ICODE] we can se memory loaction. So here a and b point to same place in memory. [CODE]>>> a = 5 >>> b = 5 >>> a is b True >>> id(a) 4062136 >>> … | |
Re: If we mix together what you have it can look like this. [CODE]def firstLetter(s): '''Count first letter in a sentence''' place = {} for item in s.lower().split(): place[item[0]] = place.get(item[0], 0) + 1 return place s = "Today is tomorrow" print firstLetter(s) #--> {'i': 1, 't': 2} help(firstLetter) #Look at … | |
Re: Make TT a datetime object with strptime. Change to datetime.now(). Now we have 2 datetime object that we can subtract. [CODE]>>> from datetime import datetime >>> TT = "2012-01-16" >>> tt_date = datetime.strptime(TT, '%Y-%m-%d') >>> tt_date datetime.datetime(2012, 1, 16, 0, 0) >>> now = datetime.now() >>> now datetime.datetime(2012, 2, 29, … | |
Re: You have to convert to int() or float(). If you concatenate two string then is just strings not numbers. [CODE]>>> '5' + '2' '52' [/CODE] [CODE]a = raw_input("enter 2 numbers separated by a /: ") #5/2 entered b = a.split("/") c = int(b[0]) + int(b[1]) print c [/CODE] You can … | |
Re: Look a a little messy,here a couple of way to write a list to a file. If you need more help post a sample of list and how you want it to look in a file. [CODE]l = ['Fauntleroy Duck', 'Mickey Mouse'] with open('names.txt', 'w') as f_out: f_out.write(', '.join(l)) '''Output--> … | |
Re: [ICODE]sort()[/ICODE] dos a in place sort of orginal list and it dont return anything. [CODE]>>> mystring = 'blue, pink, red, red, red, white, long, short, blonde, blonde' >>> s = mystring.split(', ') >>> s ['blue', 'pink', 'red', 'red', 'red', 'white', 'long', 'short', 'blonde', 'blonde'] >>> s.sort() >>> s ['blonde', 'blonde', … | |
Re: A dictionary can ofen short down long if/elif statement. Something like this. [CODE]def find_numb(phone_dict, user_input): try: return [k for k, v in phone_dict.items() if user_input in v][0] except IndexError: return('Not found') user_input = input("Enter a single letter: ") #Return a string phone_dict = {2: ('a', 'b', 'c'), 3: ('d', 'e', … | |
Re: Dont use [B]file[/B] as variable/argument is a built-in functions. [CODE]>>> f = open(file, 'a') Traceback (most recent call last): File "<interactive input>", line 1, in <module> TypeError: coercing to Unicode: need string or buffer, type found >>> file <type 'file'> >>> [/CODE] | |
Re: [QUOTE]None of these really answer my question. I want to read every line not just the final line. [/QUOTE] You could have tried to figure something yourself with the help you have gotten. I am gone write a soultion of what you want. So here is my version,i bring in … | |
Re: [QUOTE]I am new to python and cant figure out what I am doing wrong with the global variables [/QUOTE] Dont use global statement,because it is ugly. Function should receive arguments and return value/s out. Code should stay local to function,with global statement you are destoring that. Use code tag,now i … | |
Re: [QUOTE]The above code creates an array but, each element is 4 bytes each.[/QUOTE] Not an array in python we call it a list. A list in python is much more flexible than "array" as it`s called in C/C++,java. Python has 3 types ints, longs or floats. eight bits unsigned(can store … | |
Re: Hi use code tag next time,mark your code and press "code" You only find first space at index 7. The second one is at index 12 >>> name = 'francis ford coppola' >>> space=name.find(" ") >>> space 7 This: name = 'francis ford coppola' l = [] found = name.find(" … | |
Re: [QUOTE]I'm working on the py2exe convertor, which will convert files from .py to .exe[/QUOTE] It seems like you are making this to diffcult and you are missing stuff like setup option. Look at this,will convert py file to exe. [CODE]from distutils.core import setup import py2exe import sys def py2_exe(file_in=None): if … | |
Re: Just to clear tings up. Is ofile referring to a path or a file? Just a example,and you missing a else block. [CODE]import os ofile = r'c:\test4' if os.path.exists(ofile): print 'ofile exists' else: print 'ofile dont exist'[/CODE] [ICODE]os.path.exists[/ICODE] return True if path refers to an existing path. Returns False for … | |
![]() | Re: [CODE]>>> d = {'ric':24, 'ric1':46, 'ric2':23, 'mike':1, 'mike1':47} >>> l = ['ric', 'mike'] >>> for name in l: ... if name in d: ... print '{0} has a value of {1}'.format(name, d[name]) ... ric has a value of 24 mike has a value of 1[/CODE] |
Re: Here we go again:ooh: [CODE]>>> a = 1 >>> globals() {'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'a': 1, '__package__': None}[/CODE] What`s happen here is that we take a look into the global namespace. We see that global namespace store [ICODE]'a': 1[/ICODE] as a dictionary. Let create a visible … | |
Re: [CODE] >>> a = 1 >>> ranking = "a" >>> print 'ranking is %s' % globals()[ranking] ranking is 1 [/CODE] This is more of a ugly hack and dont do it like this. You are better of bulding a dictionary. Something like this [CODE] >>> d = {'ranking_a': 1, 'ranking_b': … | |
Re: [CODE]with open('numb.txt') as f: print [i.split() for i in f] #[['1', 'string1'], ['2', 'string2'], ['10', 'string3']][/CODE] A little mistake like this for 1 list. [CODE]with open('numb.txt') as f: print f.read().split() #['1', 'string1', '2', 'string2', '10', 'string3'] [/CODE] | |
Re: Just to simplify little and use better names. [CODE]import os for root, dirs, files in os.walk(r'C:\test'): for f in files: if f.startswith('roads.'): print f #print os.path.join(root, f) [/CODE] So this will print only files that starswith "roads" in directory c:\test. we iterate over files and last line we can join … | |
Re: I see that you have solved it,that`s god. I did mix something together with regex when i saw the post. Here it is not the cleanest soultion,but shoud work ok. [CODE]import re text = '''\ BEGIN:VCARD VERSION:2.1 REV:20110913T095232Z UID:aac119d5fe3bc9dc-00e17913379d6cc8-3 N;X-EPOCCNTMODELLABEL1=First name:;Maj;;; TEL;VOICE:09120000000 X-CLASS:private END:VCARD BEGIN:VCARD VERSION:2.1 REV:20110228T083215Z UID:aac119d5fe3bc9dc-00e17b0693898c98-4 N;X-EPOCCNTMODELLABEL1=First name:;Ali … | |
Re: You cannot just open an ordinary txt file with pickle. You have to dump something to it first. [CODE]# Save a dictionary into a pickle file. import pickle favorite_color = {"lion": "yellow", "kitty": "red"} pickle.dump(favorite_color, open("Ex.txt", "wb")) favorite_color = pickle.load(open("Ex.txt", "rb" )) print(favorite_color) #{'lion': 'yellow', 'kitty': 'red'}[/CODE] | |
Re: You can look at this,and type is a reserved word in python. [CODE]class Object_refs(object): def __init__(self, descriptor_type, my_type, reference_count, flags=None): '''initializer method can be compared with constructor C++,but are not the same''' self.desctype = descriptor_type self.my_type = my_type self.refcount = reference_count self.flags = flags[/CODE] Use class. [CODE]>>> descriptor_type = 1 … | |
Re: Best way to create one is to not to. [URL="http://en.wikipedia.org/wiki/Pseudorandom_number_generator"]Pseudo-random number generators[/URL] are a very complex subject, so it's better off to use the implementations produced by the people that have a good understanding of the subject. Python uses the [URL="http://en.wikipedia.org/wiki/Mersenne_twister"]Mersenne twister[/URL] as the core generator. It produces 53-bit precision … | |
Re: Almost always nothing after [ICODE]else:[/ICODE]. You have some cases like a ternary operator,list comprehension where [ICODE]else[/ICODE] is not bare. You can you use [ICODE]if[/ICODE] or [ICODE]elif[/ICODE] in this case. It is almost always best to try avoiding global statement. Pass variable in as an argument and in most cases return … | |
![]() | Re: [QUOTE]but I would at least be able to choose how many digits it goes out to, and not have it end prematurely. Do you have any suggestions?[/QUOTE] There is no problem to control how many digits you want with decimal module use [ICODE]getcontext().prec[/ICODE] or python string formatting. [CODE]>>> from decimal … ![]() |
Re: Do you use python 3 or 2? By your print statement it look like you use python 3. I dont want to reindented your code. Here is a couple basic versions that may help you. [CODE]#python 2.x import random secret_number = random.randint(1,20) counter = 0 guess = 0 print 'Guess … | |
Re: If you think of something else than code under,give an example of list and task. [CODE]>>> l = [1,2,3,4] >>> l[:2] [1, 2] >>> l[2:] [3, 4] >>> #Sum up last 2 digits >>> sum(l[2:]) 7[/CODE] | |
Re: With list comprehension it can look like this. Just a little thing capitale letters should only be used in class name. Not in function name or method name. [CODE]def gen_numbers(num): return [i for i in range(num+1)][/CODE] | |
Re: Something like this,[ICODE]with open()[/ICODE] close fileobject auto. If you want line 2 also,change [ICODE]elif[/ICODE] to [ICODE]if[/ICODE]. [CODE] #test.txt line 1 line 2 line 3 line 4[/CODE] [CODE]f_out = open('outfile.txt', 'w') flag = False with open('test.txt') as f: for line in f: if 'line 2' in line: flag = True elif … | |
Re: You most explain better,there are several scenarios for this. Look at this. [CODE]>>> s = 'foo bar foo bar foo' >>> len(s.split()) 5[/CODE] So 5 substring in s. [CODE]>>> s[:2] 'fo'[/CODE] "fo" is a substring of s. [CODE]import re [m.start() for m in re.finditer('oo', s)] [1, 9, 17][/CODE] "oo" is … |
The End.