104 Posted Topics

Member Avatar for vmars

[QUOTE=paulthom12345;711332]that just makes sure the program knows where to look to find the variables. So if more than one thing was in the formatted string you would use a tuple.[/QUOTE] It's required to enclose the variable in parentheses in this case:[code=Python]>>> a = 5 >>> b = 10 >>> print …

Member Avatar for bvdet
0
110
Member Avatar for unkwntech

The substring "\t" in [I]string[/I] is evaluated as a tab character. The [I]re[/I] method [I]match[/I] only matches at the beginning of a string. Try this: [code=Python]import re s = r'c:\test.doc' m = re.search(r":(\\[0-9a-z])", s) if m: print m.group(1) else: print m[/code]

Member Avatar for bvdet
0
134
Member Avatar for Daiosmith

The following splits the sentence up into words first, looks for the index of word 1, then looks for the index of word 2 starting after index 1. Punctuation and whitespace is stripped from each word.[code=Python]import string def words_between(s, first, second): # return the words between first and second words …

Member Avatar for shadwickman
0
109
Member Avatar for paynegm

Do not use [I]sum[/I] as a variable name, because it is a built in function. I would suggest that you not use [I]split[/I] either, because it is confusing (it is to me anyway). Use [I]sum()[/I] and [I]len()[/I] to return your values.[code]def line_sum_and_count(line): """Finds the sum and count of the numbers …

Member Avatar for jlm699
0
76
Member Avatar for jworld2

Not to be picky, but an iterable can be converted to a list with the built-in function [I]list[/I]. [code]>>> import string >>> list(string.letters) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', …

Member Avatar for jworld2
0
144
Member Avatar for knish

[QUOTE=knish;697224]i am using glob.glob('') function to get a list of all files from a folder. I need to get only those names which do not contain '_ab' in it. How is it possible. I understand the need for regular expressions here. i tried (?!....) . what should work here. example …

Member Avatar for ghostdog74
0
140
Member Avatar for Agni

Use string method [I]strip()[/I] to remove newline characters. [code=Python]for line in lines: filemenu.add_cascade(label=line.strip())[/code]

Member Avatar for Agni
0
240
Member Avatar for iamthwee

Decide what types of objects that need to be converted. If needed, create a function to make each conversion type. An exception should occur on any failed conversion. If all conversions fail, return a string. Example: [code=Python]import time def fdim(s): # return a float given a fraction (EX. '1/2') ss …

Member Avatar for bvdet
0
395
Member Avatar for Hazey

You can use escape sequence [I]\b[/I] to match exact words. [code]import re s = "I'm trying to debug a problem but the debugger is not working" target = 'debug' repl = 'fix' patt = re.compile(r'\b%s\b' % target) print patt.sub(repl, s)[/code]Gribouillis has a very nice solution. I am going to use …

Member Avatar for bvdet
0
71
Member Avatar for dineshdileep

File method [U]readline()[/U] reads an entire line from an open file at the file's current position. The file position is relocated. File method [I]tell()[/I] returns the current position. Example:[code]>>> f = open(r'D:\SDS2_7.0\macro\Work In Progress\line_numbers.txt') >>> f.tell() 0L >>> f.readline() 'Line 1\n' >>> f.tell() 8L >>> f.readline() 'Line 2\n' >>> f.tell() …

Member Avatar for zachabesh
0
89
Member Avatar for damyt01

This seems to work: [code=Python]t = 'I love cheese; cheese is my favourite besides melted cheese.' cheeses = ["shredded gorgonzola","bree","camenbert"] for s in cheeses: t = t.replace('cheese', s, 1)[/code]Here's another way using the string method [I]index()[/I] and slicing:[code=Python]def str_sub_multiple(s, target, sub_list): for sub in sub_list: try: n = s.index(target) s …

Member Avatar for bvdet
0
93
Member Avatar for g_e_young

Since I am using Python 2.3, I will define a function to pass to [I]sort()[/I]. [code=Python]def comp(a,b): return cmp(a[5], b[5]) f = open('sample_data.txt') data_list = [[float(item) for item in line.strip().split(',')] for line in f] data_list.sort(comp) f.close()[/code]When you read the information from file, each line is a string as in:[code=Python]"4, 8, …

Member Avatar for g_e_young
0
1K
Member Avatar for ndoe

Every XML document must have a declaration and a root element. I may do something like this:[code]data = """ndoe bali swimming male""" tag_list = ['name', 'home', 'hobby', 'gender'] xml_data_list = ['<?xml version="1.0" encoding="ISO-8859-1"?>','<people>'] for i, item in enumerate(data.split()): xml_data_list.append("<%s>%s</%s>" % (tag_list[i], item, tag_list[i])) xml_data_list.append('</people>') print '\n'.join(xml_data_list)[/code] Output: >>> <?xml version="1.0" …

Member Avatar for ndoe
0
111
Member Avatar for Dekudude

You don't need regex for this: [code]>>> array = ['red','blue'] >>> array1 = [' %s ' % item for item in array] >>> array1 [' red ', ' blue '] >>> [/code]

Member Avatar for Dekudude
0
130
Member Avatar for fmv2011

[QUOTE=fmv2011;659006]I indeed do get the same error. I am using version 2.2.3. Is there any way for me to get around this?[/QUOTE]The following works in Python 2.3 and may work in 2.2.[code=Python]alist = [1,3,2,5,4,7,6] alist.sort() alist.reverse()[/code]Note that methods sort() and reverse() reorder list object alist in place.

Member Avatar for Ene Uran
0
368
Member Avatar for StarryEyedSoy

My thought was to do something like the following:[code=Python]data = '''Date Open High Low Close Volume Adj 7/18/2008 19.57 20.1 17.76 19.11 50773900 19.11 7/17/2008 18.08 20.15 16.81 18.9 72725600 18.9 7/16/2008 14.27 16.85 13.47 16.65 83402200 16.65 7/15/2008 12.99 14.58 12.02 13.22 132443700 13.22 7/14/2008 16.25 16.3 12.4 12.4 …

Member Avatar for jlm699
0
133
Member Avatar for docaholic

By adding a __cmp__ method to class [I]Movie[/I], you can sort instance objects in list [I]m1[/I] with list method [I]sort()[/I]. Following is an example of a __cmp__ overload in a Vector class that sorts on the x, y and z attributes: [code=Python] def __cmp__(self, other, epsilon=0.000001): x = abs(self.x-other.x) if …

Member Avatar for docaholic
0
159
Member Avatar for ChrisP_Buffalo

You can use string formatting for your regex pattern. The following iterates on the file object. For the top 10 players, variable [I]data[/I] should have 40 items. Match object m.groups() should have 5 items. The first item will be the entire matched string. The data you are interested in will …

Member Avatar for bvdet
0
5K
Member Avatar for Mazille

It appears that you omitted an operator: yIntercept = y1 - (((y2 - y1)/(x2 - x1))[B][COLOR="Red"](add operator here)[/COLOR][/B](x1))

Member Avatar for Mazille
0
135
Member Avatar for dinilkarun

Function indexList() returns a list of indices of '-' in the string. Function strip_chrs() strips the trailing characters from the first occurrence of a letter after the last '-'.[code=Python]def indexList(s, item, i=0): """ Return an index list of all occurrances of 'item' in string/list 's'. Optional start search position 'i' …

Member Avatar for woooee
0
416
Member Avatar for linip

Convert the integers to strings with a list comprehension and use string method join() to combine:[code=Python]>>> a=[0,1,2,3,4] >>> print ''.join([str(i) for i in a]) 01234 >>> [/code]

Member Avatar for bvdet
0
73
Member Avatar for k.wiseman

You are returning a tuple in cun_to_centimeters(). Access the elements of the tuple by slicing. Example: [code=Python]>>> def ret_tuple(): ... return 1, 2 ... >>> obj = ret_tuple() >>> obj[0] 1 >>> obj[1] 2 >>> [/code]

Member Avatar for k.wiseman
0
120
Member Avatar for dinilkarun
Member Avatar for dinilkarun
0
232
Member Avatar for mengqing

The string method splitlines() can preserve trailing newlines.[code]>>> string.splitlines(1) ['Hello\n', 'World'] >>> [/code]

Member Avatar for bvdet
0
105
Member Avatar for dr_kac

Here is an example using woooee's suggestion: [code]s = '''ABCD vvvv 1e-12 ABCD hhhh 1e-6 ABCD ggggg 1e-3 ASDE ffffff 1e-57 ASDE dddd 0.001''' dd = {} for item in s.split('\n'): itemList = item.split() if itemList[0] in dd: if float(dd[itemList[0]][1]) > float(itemList[2]): dd[itemList[0]] = itemList[1:] else: dd[itemList[0]] = itemList[1:] for …

Member Avatar for paddy3118
0
188
Member Avatar for indu_shreenath

The other solutions offered work fine. If you want to use a regular expression, the following may work also:[code=Python]import re patt = re.compile(r'call +(?!%\S+%)') print patt.match('call %_junk% text1') print patt.match('call GetFiles %Label%')[/code]This matches the word 'call' at the beginning of the line followed by any number of spaces if not …

Member Avatar for bvdet
0
103
Member Avatar for cheechand

>>> s = 'airplane' >>> list(s) ['a', 'i', 'r', 'p', 'l', 'a', 'n', 'e'] >>>

Member Avatar for lllllIllIlllI
0
69
Member Avatar for spoksss

Try this: [code=Python]filters = {'small': DateFormat.small, 'big': DateFormat.big}[/code] This works in Python 2.3:[code=Python] import sys class DateFormat(object): """Class to format and translate date to polish""" labels = { 'monday' : u'poniedziałek', 'tuesday' : u'wtorek', 'wenesday' : u'środa', 'thursday' : u'czwartek', 'friday' : u'piątek', 'saturday' : u'sobota', 'sunday' : u'niedziela', } …

Member Avatar for bvdet
0
127
Member Avatar for parmenio79

Iterate on all the list elements except the last one: [code=Python]numblist = [1, 2, 3, 5, 6, 7, 8, 9, 11] for i in range(len(numblist)-1): if numblist[i] == numblist[i + 1] - 1: print 'NO GAP between indexes %d and %d' % (i, i+1) else: print 'GAP between indexes %d …

Member Avatar for parmenio79
0
27K
Member Avatar for atsuko

I am guessing that you used 'str' as a variable name. [code]>>> str = 'abc' >>> print str(123.456) Traceback (most recent call last): File "<interactive input>", line 1, in ? TypeError: 'str' object is not callable >>> del str >>> print str(123.456) 123.456 >>> [/code]

Member Avatar for atsuko
0
156

The End.