880 Posted Topics

Member Avatar for hughesadam_87

>>> 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']

Member Avatar for snippsat
0
188
Member Avatar for HTMLperson5

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 …

Member Avatar for HTMLperson5
0
2K
Member Avatar for shean1488

> 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 …

Member Avatar for shean1488
0
133
Member Avatar for bkjfdghiuds

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 …

Member Avatar for snippsat
0
2K
Member Avatar for 4evrmrepylrning

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']

Member Avatar for 4evrmrepylrning
0
218
Member Avatar for debasishgang7

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'), …

Member Avatar for TrustyTony
0
1K
Member Avatar for strongguy12345

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, …

Member Avatar for strongguy12345
0
328
Member Avatar for webstart

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 = [] >>> …

Member Avatar for vegaseat
0
6K
Member Avatar for MunkyCheez

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: …

Member Avatar for woooee
0
4K
Member Avatar for utkarshsahu

> 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

Member Avatar for utkarshsahu
0
175
Member Avatar for lisa92222

You can try binarie install from this site. http://www.voidspace.org.uk/python/modules.shtml#pycrypto

Member Avatar for TrustyTony
0
191
Member Avatar for C0ding

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 …

Member Avatar for C0ding
0
417
Member Avatar for meli123

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' % …

Member Avatar for snippsat
0
113
Member Avatar for LDJ95

> 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 …

Member Avatar for LDJ95
0
850
Member Avatar for adrigreat14

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 …

Member Avatar for adrigreat14
0
281
Member Avatar for snippsat

Where is sticky treads starting python,Gui programming....? These were very good treads and should be sticky.

Member Avatar for TrustyTony
0
103
Member Avatar for 4evrmrepylrning

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> …

Member Avatar for Gribouillis
0
277
Member Avatar for utkarshsahu

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 …

Member Avatar for snippsat
0
411
Member Avatar for boiishuvo

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> …

Member Avatar for snippsat
0
287
Member Avatar for boiishuvo

[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 …

Member Avatar for boiishuvo
0
448
Member Avatar for hughesadam_87

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 >>> …

Member Avatar for Gribouillis
0
166
Member Avatar for MegaMan15

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 …

Member Avatar for TrustyTony
0
222
Member Avatar for Matjame

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, …

Member Avatar for Matjame
0
754
Member Avatar for straylight

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 …

Member Avatar for straylight
0
350
Member Avatar for KickAssElmo

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--> …

Member Avatar for KickAssElmo
0
234
Member Avatar for HoneyBadger

[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', …

Member Avatar for HoneyBadger
0
124
Member Avatar for layneb131

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', …

Member Avatar for woooee
0
490
Member Avatar for Lucaci Andrew

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]

Member Avatar for Lucaci Andrew
0
311
Member Avatar for oberlin1988

[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 …

Member Avatar for Lucaci Andrew
0
3K
Member Avatar for sc0tty

[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 …

Member Avatar for sc0tty
0
210
Member Avatar for DanWebb3148

[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 …

Member Avatar for DanWebb3148
0
973
Member Avatar for ComputerGirlie

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(" …

Member Avatar for ComputerGirlie
0
640
Member Avatar for Lucaci Andrew

[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 …

Member Avatar for Lucaci Andrew
0
321
Member Avatar for floatingshed

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 …

Member Avatar for snippsat
0
163
Member Avatar for apeiron27

[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]

Member Avatar for snippsat
0
74
Member Avatar for ron126

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 …

Member Avatar for snippsat
0
241
Member Avatar for ron126

[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': …

Member Avatar for ron126
0
240
Member Avatar for mr_noname

[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]

Member Avatar for snippsat
0
269
Member Avatar for kungfubambi

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 …

Member Avatar for kungfubambi
0
245
Member Avatar for M.S.

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 …

Member Avatar for snippsat
0
2K
Member Avatar for Irina77

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]

Member Avatar for Irina77
0
194
Member Avatar for LdaXy

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 …

Member Avatar for LdaXy
0
225
Member Avatar for inuasha

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 …

Member Avatar for snippsat
0
3K
Member Avatar for Duane Vick

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 …

Member Avatar for snippsat
0
2K
Member Avatar for Mouche

[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 …

Member Avatar for Mouche
0
244
Member Avatar for drlockdown

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 …

Member Avatar for snippsat
0
194
Member Avatar for pwolf

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]

Member Avatar for pwolf
0
4K
Member Avatar for pwolf

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]

Member Avatar for TrustyTony
0
2K
Member Avatar for Joelx

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 …

Member Avatar for Joelx
0
181
Member Avatar for hisan

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 …

Member Avatar for snippsat
0
157

The End.