Write a function, called constrainedMatchPair which takes three arguments: a tuple representing starting points for the first substring, a tuple representing starting points for the second substring, and the length of the first substring. The function should return a tuple of all members (call it n) of the first tuple for which there is an element in the second tuple (call ... |
|
|
#!/usr/bin/python import weechat import os weechat.register("RhythmboxNP", "Cody Mitchell", "1.0", "GPL", "Rhythmbox NP", "", "") def do_np(data, buffer, args): run_ct = os.popen("quodlibet --print-playing", "r") currenttrack = run_ct.read() currenttrack = currenttrack.split(" - ") ... |
How do I make python ignore empty strings? The following snippet seems to work. However, if self.entry2.get() is empty it gives me an error, how do I make it ignore the command if the string is empty? Snippet: Code: Select all if self.var2.get() == 'atm': ... |
inp = [ 'what time is it?', 'what time is it!', 'what time is it#$(*$'] import re base = 'what time is it' regex = re.compile(base + '.*', re.IGNORECASE) for test in inp: print test print regex.match(test) print test.lower().startswith(base) ... |
for path in paths: try: if path.index("HKEY_LOCAL_MACHINE\\SOFTWARE\Microsoft\\") == 0: print "match:", path except: print "does not match:", path |
|
Uptill so far I am able to achieve only this Code: Select all def insert_tag(pattern,sentence): pattern_lst = pattern.split() pattern_index = [] sentence_lst = sentence.split() for index,item in enumerate(sentence_lst): if item ... |
I am trying to write a function that will search through a string finding a target. Everytime the target is found, I want the function to give me the starting index location where it is found. So far I can get it to print a list with empty strings for every occurrence of target. Here is the code for the function: ... |
10. Strings python-forum.org |
|
|
q = 'fake_file'' las_loc = 'c:\\temp\\fake' ext_out = '.las' for q in list_split: print q string_loc = las_loc + "\\" + q + out_ext ... |
|
lotdict = {'fl':float(95), 'wwhe':float(200), 'qqb':float(183), 'cnc':float(918)} strlotname=None while strlotname != "": #while loop ends when user simply hits enter strlotname = raw_input("Enter lot name: ") print lotdict[strlotname.lower()] #need to reset strlotname else the while loop won't end #even if ... |
Im wondering if there is a way to add one string into a certain range within another. For example, given the two following strings. String 1: Lexis drives well. String 2: her Lexus How does one add String 2 to String 1 at a range of 13 so that the resulting string reads: Lexis drives her Lexus well. I understand that ... |
|
|
|
|
21. Strings python-forum.orgCan i get some help on these problems? Thanks a) Write a function that given a string s and a number n, prints the string s n times (once per line) b) Write a function that prints all the numbers from 0 to 1000 (not including 1000), counting by 17. c) Write a function that, given a number n, returns a ... |
I have a string with a particular character appearing in the string only once. I would like to delete whatever appears after that character including the character itself. How do I do it. For example a = "This is : a big house" I would like to remove everything after the ':' character The output string should be This is |
Code: Select all def Letter(text, number): # Checks if the string is long enough to accomodate the number selected if number > len(text): return "The number you chose is bigger than the length of your string!" else: # Checks to ... |
def tiles(): import random x = (['0']*428)+(['1']*214)+(['G', 'F', 'I', 'H', '?', '>', 'A', '@']*9) random.shuffle(x) x += '|5^396,300' ite = 0 while ite <= 30: ite += 1 y = (random.randint(1, ... |
Hello, I am trying to store in a string the name of a file located on a FTP server using ftplib. Example: [code]result = str(ftp.retrlines('NLST')) [/code] When I type the code below in the interactive shell, the output result I see on the screen is filename.extension However, when I print the value of the result variable, it showing "226 Transfer OK" ... |
can someone expand on this? apparently tupples are also immutable. if i have x = "string" i can change that to x = "strung" at some point, but is that the same variable refferring to a different string and the string hasn't changed as such? i'm just a bit foggy, can someone flesh out this concept for me, please. |
trouble with a global string by Pip Wed Jul 22, 2009 11:47 am I thought that I would make a little text adventure game as an exercise to test the python I've learned so far. I haven't even started the actual game itself, and I'm already having problems. What I thought I would do is create a class called Txt. ... |
def dig_only(str_in): new_str = '' for chr in str_in: if chr.isdigit(): new_str += chr return new_str x = dig_only('abc123de') print x, len(x) x = dig_only('qwe987rty') print x, len(x) |
Code: Select all >>> for line in fileinput.input(): ... MultiLines.append(line) ... This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty. If a filename is '-', it is also replaced by sys.stdin. To specify an alternative list of filenames, pass it as the first argument to input(). A single file name ... |
how do i make 6 new strings though, i want to take the enrty and re-package it into seperate strings so can deal with it one piece at a time? OR is there a way to designate which line of a multi line string i want pythn to "look" at? i remember from the tutorial you can ask it to look ... |
response = raw_input("\nDo you enjoy being a student at college? ").lower() while response != ("yes" or "no"): response = raw_input("I'm sorry I didn't understand your answer, please answer yes or no. ") if response == "yes": print "\nI'm glad you are enjoying it." elif response == "no": print "\nI'm ... |
I started programming again because I fell in love with Python. One part of what Im doing is rewriting an editor that I originally wrote in C. The file is one big string (up to a megabyte) with extensive simple markup indicating the number of words to follow, e.g., {1}Hello, {4}how are you today, for synchronization purposes with another file. Extensive ... |
I started programming again because I fell in love with Python. One part of what Im doing is rewriting an editor that I originally wrote in C. The file is one big string (up to a megabyte) with extensive simple markup indicating the number of words to follow, e.g., {1}Hello, {4}how are you today, for synchronization purposes with another file. Extensive ... |
|
I have multiple name fields with different names which occur more than once. i.e there is a structure like NAME : JACK #Some data NAME : JOHN #Some data NAME : PAUL #Some data NAME : JACK #Some data NAME : PAUL #Some data NAME : JOHN #Some data . . . . I want the output as: JACK JOHN PAUL ... |
|
import os, sys import time sys.stdout.write(os.popen('clear').read()) print "\n\t\t\tWelcome to the startup delay program. \n\n " raw_input("Press enter to step into the shoes of the average windows user. ") print "\n|", for i in range(30): time.sleep(0.3) print "=", print "|" print "\nJob\'s done! you can now start using the program. And kids - remember what you learned watching ... |
def main(): # months is a list used as a lookup table months = [ "January", "February", "March", "April", "May", "June", "July", "August", ... |
Hello World! I have just started trying to learn python (with absolutely no other programming experience other than "Hello world" in several diffrent laguages) My question, is simple, I hope. And really isn't so much trouble as much as it is generally me wondering. Anyway i've been using strings and getting all sorts of sentences printing on my screen, all great ... |
class X(object): def __init__(self, x, y): self.point = (x,y) def move_mouse(self, x, y): print 'old: x=%s y=%s' % (self.point[0], self.point[1]) self.point = (x, y) ... |
|
f = open('before.txt') lines = [line.strip() for line in f] f.close() # lines now holds everything in the file # next, we'll split the file into different chunks data = [] current = '' for line in lines: if line.startswith('>'): # grab the current data element ... |
|
Thanks, I'm pretty sure I can get that to work as I want it to. Now, though, I've got two related questions that are bothering me. First: is there anyway to coerce a string into a valid variable name? You can coerce and integer to a string or a string to an integer, but is there anyway to use a generated ... |
Hello all, I've got some float output, which I converted to a string in order to be able to display it in a GUI, looking like this: 591.52825554 However I only need this result to two decimal places at the most; what I don't know is how to tell Python to truncate (or round? Accuracy isn't really the issue here, so ... |
class A(object): def identify(self): print "I'm an A instance" class B(object): def identify(self): print "I'm a B instance" d = {"A":A(), "B":B()} data = ["A", "B"] for name in data: d[name].identify() --output:-- I'm ... |
|
48. STRINGS! python-forum.orgHow can i separate integers entered into a raw_input as a string. I want to be able to separate these integers add then all together then take the sum of those numbers, separate them and add them together all the way down until the sum is a single digit. Then i have to figure out a way to count how many ... |
>>> l ['c:\\one.shp', 'c:\\two.shp'] >>> for i in l: i 'c:\\one.shp' 'c:\\two.shp' >>> g = open(i+'.xml', 'w') >>> g >>> g.write('metadata'+i) >>> g.close() >>> g h=open(g).read() Traceback (most recent call last): File "", line 1, in h=open(g).read() ... |
fin=open('VIM.TXT','r') fout=open('VIM.SQL','w') sql='SELECT CONT_ID, PRJ_NBR, LN_ITM_NBR, SMPL_ID, SMPL_TST_NBR, PROPVAL,\n' sql+='CASE\n' fout.write(sql) tpl='WHEN (PROPVAL > $a AND PROPVAL <= $b) THEN $c \n' a=2.7 for line in fin.readlines(): sql=tpl sql.replace('$a',str(a)) sql.replace('$b',str(a+0.1)) sql.replace('$c',line.strip()) fout.write(sql) a+=0.1 sql='ELSE ... |
This is probably a very simple problem, but I cant seem to solve it And I did read through the Converting String to Code thread, but I didnt find it helpful (or found it confusing). I have a string, say, (* 4 5 7 9), and I want to extract all of the characters in order to evaluate the expression 4*5*7*9. ... |
|
Hello I have strings I need to convert to lists. The string might start with whitespace, then an option, and then as many values you want, seperated by whitespace. The string might end with a comment. Code: Select all # Example strings x = " Option Value #Comment" z = "AnotherOption Value ... |
import sys, traceback def formatExceptionInfo(level=3): error_type, error_value, trbk = sys.exc_info() info_list = ["Error: %s \nDescription: %s \nTraceback:\n" % \ (error_type.__name__, error_value), ] info_list.extend(traceback.format_tb(trbk, level)) return ''.join(info_list) def xxx(a, ... |
|
|
|
Beat me to it. However, there's one thing I would do differently is the right substring. Instead of d = a[10:], I would use d = a[-5:]. The effect is the same, but saves having to know the length of the string. The '-5' simply means start at 5 from the right, and the ':' with nothing after it means go ... |
Hi all, It is my first post on the forum so sorry if I do any mistake and for English.I am new user for the python programming because before two day I started it ,I were reading that if we want to add two strings then we can use "+" for it .But as we know that "+" does not provide ... |
What i was thinking of is, basically, making a phonebook in python that simply lets me select the name i want to call, automatically starts 'C:\Program Files\VoipCheapCom\VoipCheapCom.exe' when i select one, inputs the number and clicks "Ok" for the call for me. The thing i can't figure out is how to open voipcheapcom.exe, simply, as if i just ran it in ... |
|
def str_sort(str_in,ord_in): # function to return a string sorted in specified order # example: if str_in is 'plaha', and ord_in is the list [2,1,0,3,4], return # 'alpha' (use the list in ord_in to return characters in the correct order) if len(str_in) == len(ord_in): new_str = ''.join(str_in[i] for i in ... |
Hi, I'm trying to use the Universal Serial Port Python Library to communicate using my serial port. I've gotten the library to work, but I'm running into trouble when I'm trying to send out raw data. Here's some code to show what I'm talking about: Code: Select all >>> from uspp import * >>> tty=SerialPort("COM12", 19200) >>> tty.write("a") >>> a= [0, ... |
Hi! I have many ranges and I want to put them as a non overlapping string together. The ranges are shown as '>', the spaces in between as '-'. E.g. string length = 30 a = range(5, 10) b = range(17, 20) should give: ---->>>>>------>>>>---------- If the ranges are overlapping, they must be put in a new string. Could someone give ... |
Hey! I'm very new to programming so please forgive any obvious blunders. I've been reading a book on python but its very boring so I decided to get stuck in with a problem I have. Basically I need to take a sentence, split it into words and then export those words to separate cells in excel. I know excel can do ... |
Hi, I am facing a problem to insert a tag in the string. Pattern = PROTEIN appear_V prevent_V activation_N PROTEIN Sentence = ' IL-10 appear_V to_T prevent_V activation_N of_I NF-kappaB by_I preserve_V IkappaB-alpha protein_N level_N ,_, lead_V to_T a_D reduction_N in_I TNF-alpha release_N ._.' In the pattern PROTEIN stands for ....... I want to ... |
Hi, I think I am not clear in my question let me rephrase that: I have a lot of texts in the form of string as given below str_string ='Microsoft and IBM are located in U.S.' and for every string, I have the charoffset position of the entites I am interested to labelled for example for the above example I have ... |
def EvtChar(self, event): key = event.GetKeyCode() s = str(chr(key)) if s.isalnum() or s=='-' or s=='_' or s=='.': event.Skip() |
How can one read 5 bits from a file at a time? I'm trying to LZW-decompress a chunk of data which i suspect is LZW compressed. It therefore needs to be read in with 4 bits at a time until all 16 places are full at which point it switches to 5 bit etc... |
|
The range statement does generate a list, and the [x:y] syntax is called slice. So these are two different things and you can't use a list as index to a string. What are you expecting your code to do? Take from position 1 a substring of length 34, so leave the first character (string index 0) out and limit the length? ... |
Hi, I have a file with a lot of the following ocurrences: denmark.handa.1-10 denmark.handa.1-12344 denmark.handa.1-4 denmark.handa.1-56 ... distributed randomly in a file. I need to convert each of this ocurrences to: denmark.handa.1-10_1 denmark.handa.1-12344_1 denmark.handa.1-4_1 denmark.handa.1-56_1 so basically I add "_1" at the end of each ocurrence. I thought about using sed, but as each "root" is different I have no clue ... |
Code: Select all #! /usr/local/bin/python # my first python program import os import sys ffmpeg = 'ffmpeg -i ' # definimos variables vcd = ' -deinterlace -target pal-vcd ' dvd = ' -deinterlace -target pal-dvd ' error = ' invalid option ' f = open('configuracion.txt', 'w') #creamos archivo de configuracion ruta_in = raw_input('Path to video: ') #pedimos entrada ruta video ... |
>>> for x in xrange(5): ... for letter in "abc": ... print "http://www.marealtor.com/content/FindARealtor.htm?page_id=%s&inCtx7action=4&inCtx7pg=%s&inCtx7view=6&inCtx7order_by=R&site_id=1&minor=0&major=3&inCtx7mem_id=mem_id&inCtx7char=%s&inCtx7searchParam=29_A_A_&inCtx7dir_id=29" % (x, letter) ... Traceback (most recent call last): File "", line 3, in TypeError: not enough arguments for format string |
I have a database with variable numbers of columns which I want to quickly load from a file into a 2d list ( (..row..),(..row..), ... ) One of the columns contains text with quotes in it. My idea was to create a file like this: ("a","b","c","d") ("e","f","g","this has a "quote" in it") ... and do for line in file : list.append(eval(line)) ... |
|
example: [code] if '!paper' in word[3] and word[4] is null: ## null as in the word doesn't exist..there's nothing there. i tried a len(word_eol[0]) but it gives me # of characters in the array, not number of words which is what i would like. I don't want to parse it out. [/code] that's what I want to do... im not sure ... |
|
I'm trying to create a program which from a text input, creates a new encrypted one, doing certain operations based on a "key", etc.. and them outputting the result as a new string. So far I've gotten everything right using a series of ifs. My only problem now is I need to create a string containing all the non-alphanumerals in ASCII ... |
Hi, Need help to filter the proper value from a string, Here is a display from a ping command: Code: ( text ) Pinging 10.2.3.6 with 32 bytes of data: Request timed out. Request timed out. Request timed out. Ping statistics for 10.2.3.6: Packets: Sent = 3, Received = 2, Lost = 1 (66% loss), Here is the result of my ... |
Hello, I am trying to create an object that acts as a temporary file handle. This object should act like a standard string (and be seen as one), but upon deletion it should attempt to delete the file it is a path to. So when the object goes out of scope it will delete the temporary file. I've tried just creating ... |
|
Hi, You appear to treat this forum as a place where you can get free programming services. I've never seen you post a single line of code that you've written. Instead, you parcel out jobs you want done, and then you apparently piece those jobs together into a program. If you want to learn how to program, start writing some code. ... |
csvLabel2 = Label(self.csvFrame,padx=15,wraplength=275,justify=LEFT, text="To use data stored in a CSV file " ... |
import MySQLdb as mysql conn = mysql.connect( host="127.0.0.1", port = 3306, user = "root", passwd = "", db = "mydb1", ... |
mystring="the ip is 192.168.0.123 the time is 20.30" ip=[] for item in mystring.split(): if item.count(".") == 3: for digit in item.split("."): if digit.isdigit() and len(digit) >0 and len(digit) <=3: ... |
import string def shiftchrs(s, shift): # Shift characters A-Z and a-z (65-90 and 97-122) s1 = ''.join([chr(i) for i in range(65,123) if i not in range(91,97)]) s2 = s1[:26][shift:]+s1[:26][:shift]+s1[26:][shift:]+s1[26:][:shift] m = string.maketrans(s1,s2) return string.translate(s, m) shift = -4 s = "Scramble ... |
# create a string class that is mutable class Mstr(list): """a mutable string via inherited list and join""" def __str__(self): return ''.join(self) # text assignment has to be this way ... ms = Mstr("hello") ms[0] = 'j' print ms ... |
|
So i've got a list of the form ['tx', 'ca', 'wi', 'ny'] . I'd like to do something like: for item in list: self.%s_state % item = "somevalue" where "%s_state" is obviously a variable. I know that I can make similar function calls with getattr - is there something analogous for variables? |
If i want to put 2 string into a string what i have looks something like firstname = raw_input("give me your 1st name") lastname = raw_input("now the surname...") print = "Hello %s %s" %firstname %lastname This doesn't work, it does if i do just 1 %s ...how do i get the 2nd? thanks. rookie |
|
# show the difference in two strings a = 'c:/pictures/golf/frank' b = 'c:/pictures/golf/dick' # convert to a list alist = a.split('/') blist = b.split('/') dlist = [(x, y) for (x, y) in zip(alist, blist) if x != y] print dlist # [('frank', 'dick')] okay, that works nicely! print # problems here a = 'c:/pictures/golf/frank/secret' b = 'c:/pictures/golf/frank' # convert ... |
import itertools def tristr(): for n in itertools.count(1): t = '' while n > 0: n, d = divmod(n, 3) ... |
Looks like I have nothing else to do, so I took the liberty of timing a few has digits functions ... Code: Select all # a number of has digits functions # returns True if here are any numbers 0-9 in a string import re def has_digits1(str1): for c in str1: ... |
|
|
Code: Select all for i in os.listdir(temp_path): output_name="raster_out" # Check to see if the files extension is ascii (ignore all others) if i[-1]=='c' and i[-2]=='s' and i[-3]=='a' and i[-4]=='.': # Input ascii files complete path ... |
|
combining strings to get class member by GrandMasterP Thu Nov 23, 2006 6:01 pm Ok, this is pretty easy problem, but I can't seem to figure it out and noboby seems to know what I'm talking about when I try to explain it. Basically, I have a nested tree where each object in the tree is a node that can ... |