What is the easiest way to compare strings in Python, ignoring case?
Of course one can do (str1.lower() <= str2.lower()), etc., but this created two additional temporary strings (with the obvious alloc/g-c ... |
What method do I call to get the name of a class?
|
How do I create a file-like object (same duck time as File) with the contents of a string?
|
In PHP, a string enclosed in "double quotes" will be parsed for variables to replace whereas a string enclosed in 'single quotes' will not. In Python, does this also apply?
|
What's the easiest way of me converting the simpler regex format that most users are used to into the correct re python regex string?
As an example, I need to convert this:
string ...
|
I know that python has a len() function that is used to determine the size of a string, but I was wondering why its not a method of the string object.
Update
Ok, ... |
Is there a Python class that wraps the file interface (read, write etc.) around a string? I mean something like the stringstream classes in C++.
I was thinking of using it to ... |
|
I have many emails coming in from different sources.
they all have attachments, many of them have attachment names in chinese, so these
names are converted to base64 by their email clients.
When I ... |
In Python, if I do this:
print "4" * 4
I get
> "4444"
In Perl, I'd get
> 16
Is there an easy way to do the former in Perl?
|
I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python.
I'd rather be strict than ... |
I'm trying to figure out what the following line does exactly - specifically the %%s part?
cursor.execute('INSERT INTO mastertickets (%s, %s) VALUES (%%s, %%s)'%sourcedest, (self.tkt.id, n))
Any good mini-tutorial about string formatting and ... |
What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length?
|
I'm using urllib2 to read in a page. I need to do a quick regex on the source and pull out a few variables. I'm new to python so I'm struggling ... |
Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string?
For example:
asimpletest -> Asimpletest
aSimpleTest -> ...
|
I'm tackling project euler's problem 220 (looked easy, in comparison to some of the
others - thought I'd try a higher numbered one for a change!)
So far I have:
D ...
|
In Python, the where and when of using string concatenation versus string substitution eludes me. As the string concatenation has seen large boosts in performance, is this (becoming more) a stylistic ... |
I am doing something like this:
class Class(object):
def __init__(self):
self.var=#new instance name string#
How do I make the __ ... |
Is there a standard way to associate version string with a python package in such way that I could do the following?
import foo
print foo.version
I would imagine there's some way to retrieve ... |
This is good:
import string
string.capwords("proper name")
'Proper Name'
... |
I want to avoid calling a lot of isinstance() functions, so I'm looking for a way to get the concrete class' name for an instance variable as a string.
Any ideas?
|
In C++, I could do:
for(int i = 0; i < str.length(); ++i)
std::cout << str[i] << std::endl;
How do I iterate over a string in Python?
|
Hey there, I'm kind of new to Python and I'm trying to make a basic application that builds a string out of user input then adds it to the win32 clipboard. ... |
I have a name as a string, in this example "markus johansson".
I'm trying to code a program that makes 'm' and 'j' uppercase:
name = "markus johansson"
for i in range(1, len(name)):
...
|
Original Question
I have made a function which is waiting for a particular string to appear on a serial port, and returns all character read until the string was found, or false ... |
If I am evaluating a Python string using eval(), and have a class like:
class Foo(object):
a = 3
def bar(self, x): return x + a
What ... |
I have a script that uses the cmd Python module. The cmd module uses a triple quoted multiline string as it's help text. Something like this
def x(self, strags = None):
...
|
I have a question regarding the "standard" way to put comments inside Python source code:
def func():
"Func doc"
... <code>
'TODO: fix ...
|
I'm trying to write a video application in PyQt4 and I've used Python ctypes to hook into an old legacy video decoder library. The library gives me 32-bit ARGB data and ... |
In the following example what is cached correctly? Is there a Vary-Header I have to set server-side for the GET string?
import httplib2
h = httplib2.Http(".cache")
resp, content = h.request("http://test.com/list/")
resp, content = h.request("http://test.com/list?limit=10")
resp, content ...
|
BASE_URL = 'http://foobar.com?foo=%s'
variable = 'bar'
final_url = BASE_URL % (variable)
I get this 'http://foobar.com?foo=bar' # It ignores the inside string.
But i wanted something like this 'http://foobar.com?foo='bar''
Thanks for the answer.
Can ... |
How to use a string containing a class name to reference a class itself?
See this (not working) exemple...
class WrapperClass:
def display_var(self):
...
|
Is there a way to write a string directly to a tarfile? From http://docs.python.org/library/tarfile.html it looks like only files already written to the file system can be added.
|
I have a simple python script like so:
import sys
lines = sys.argv[1]
for line in lines.splitlines():
print line
I want to call it from the command line (or a .bat file) ... |
I need to write a function in python that gets a string-
If the first or last characters in the string are spaces, then they should be removed (both). If not than ... |
I'd like to use os.system("md5sum myFile") and have the result returned from os.system instead of just runned in a subshell where it's echoed.
In short I'd like to do this:
resultMD5 = os.system("md5sum ...
|
I know that you can use the ctypes library to perform case insensitive comparisons on strings, however I would like to perform case insensitive replacement too. Currently the only way I ... |
I want a string with one additional attribute, let's say whether to print it in red or green.
Subclassing(str) does not work, as it is immutable. I see the value, but it ... |
I have a wxPython program with two processes: A primary and a secondary one (I'm using the multiprocessing module.) The primary one runs the wxPython GUI, the secondary one does not. ... |
Suppose this is my list of languages.
aList = ['Python','C','C++','Java']
How can i write to a file like :
Python : ...
C ...
|
I run into follow problem. Did I miss anything?
Association.all().count()
1
Association.all().fetch(1)
[Association(**{'server_url': u'server-url', 'handle': u'handle2', 'secret': 'c2VjcmV0\n', 'issued': 1242892477L, 'lifetime': 200L, 'assoc_type': u'HMAC-SHA1'})]
Association.all().filter('server_url =', 'server-url').count()
0 # expect 1
Association.all().filter('server_url =', u'server-url').count()
0 # expect 1
Association.all().filter('issued ...
|
Just getting into python, and so I decided to make a hangman game. Works good, but I was wondering if there was any kind of optimizations I could make or ways ... |
I'm trying to test for a /t or a space character and I can't understand why this bit of code won't work. What I am doing is reading in a file, ... |
I can't see why this won't work. I am performing lstrip() on the string being passed to the function, and trying to see if it starts with """. For some reason, ... |
I need a simple program that given a string, returns to me the next one in the alphanumeric ordering (or just the alphabetic ordering).
f("aaa")="aab"
f("aaZ")="aba"
And so on.
Is there a function for this ... |
I want to print a character or string like '-' n number of times.
Can I do it without using a loop?.. Is there a function like
print('-',3)
..which would mean printing the - ... |
I would like to write a program that changes my user agent string.
How can I do this in Python?
|
I want to write a program that changes the HTTP headers in my requests that are sent by my web-browser. I believe it can be done with a proxy server. So, ... |
I have taken an integer input and tried to reverse it in Python but in vain! I changed it into a string but still I am not able to. Is there ... |
Possible Duplicate:
How can I capture the stdout output of a child process?
I'm running a cat-like program in bash from Python:
import ...
|
I'm working on a plugin for Trac and am inserting some javascript into the rendered HTML by manipulating the Genshi stream.
I need to test if a javascript function is already in ... |
I have 3 text files
- many lines of
value1<tab>value2 (maybe 600)
- many more lines of
value2<tab>value3 (maybe 1000)
- many more lines of
value2<tab>value4 (maybe 2000)
Not all lines match, some will have one or more ... |
I'm writing a game engine using pygame and box2d, and in the character builder, I want to be able to write the code that will be executed on keydown events.
My plan ... |
In trying to capitalize a string at separators I encountered behavior I do not understand. Can someone please explain why the string s in reverted during the loop? Thanks.
s ...
|
I have done this operation millions of times, just using the + operator! I have no idea why it is not working this time, it is overwriting the first part ... |
I was trying to simplify the code:
header = []
...
|
I was trying to figure out which integers python only instantiates once (-6 to 256 it seems), and in the process stumbled on some string behaviour I can't see the pattern ... |
I have a class like the following:
class User:
def __init__(self):
self.data = []
self.other_data ...
|
So, I have learnt that strings have a center method.
>>> 'a'.center(3)
' a '
Then I have noticed that I can do the same thing using the 'str' object which is a type, ... |
Using Python I want to create a property in a class, but having the name of it in a string. Normally you do:
blah = property(get_blah, set_blah, del_blah, "bleh blih")
where get_, set_ ... |
I have failed to find documentation for the operator % as it is used on strings in Python. Does someone know where that documentation is?
|
When I run doctests on different Python versions (2.5 vs 2.6) and different plattforms (FreeBSD vs Mac OS) strings get quoted differently:
Failed example:
decode('{"created_by":"test","guid":123,"num":5.00}')
Expected:
{'guid': ...
|
I have written information to a file in python using struct.pack
eg.
out.write( struct.pack(">f", 1.1) );
out.write( struct.pack(">i", 12) );
out.write( struct.pack(">3s", "abc") );
Then I read it in java using DataInputStream and readInt, readFloat and ... |
I need to generate unique record id for the given unique string.
I tried using uuid format which seems to be good.
But we feel that is lengthly.
so we need to ... |
I've written some Python code that fetches a zip file from the web and into a string:
In [1]: zip_contents[0:5]
Out[1]: 'PK\x03\x04\x14'
I see there's a zipfile library, but I'm having trouble finding a ... |
Is there any efficient mass string concatenation method in Python (like StringBuilder in C# or StringBuffer in Java)? I found following methods here:
- Simple concatenation using '+'
- Using UserString from MutableString ...
|
What is a one-liner code for setting a string in python to the string, 0 if the string is empty?
# line_parts[0] can be empty
# if so, set a to the string, ...
|
Python beginner question. Code below should explain my problem:
import Image
resolution = (200,500)
scaler = "Image.ANTIALIAS"
im = Image.open("/home/user/Photos/DSC00320.JPG")
im.resize(resolution , scaler)
RESULT:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ...
|
How can I revert back to the default function that python uses if there is no __str__ method?
class A :
def __str__(self) :
return ...
|
In Python and GAE, I would like to ask how to get the parameters of a query string in the url.
As I know, the query_string part returns all the ... |
In Python, what is the simplest way to execute a local Linux command stored in a string while catching any potential exceptions that are thrown and logging the output of the ... |
My emacs hangs (Ubuntu 9 + emacs 23 + pyflakes) when I type """ quotes for string blocks.
anybody experience the same problem? I think, it may not be the emacs problem ... |
I am needing to unserialize a string into an array in python just like php and then serialize it back.
|
I would like to run a process from Python (2.4/2.5/2.6) using Popen, and I
would like to give it a string as its standard input.
I'll write an example where the process does ... |
I had a combinatorics assignment that involved getting every word with length less than or equal to 6 from a specific combination of strings. In this case, it was S ... |
This is partially a theoretical question:
I have a string (say UTF-8), and I need to modify it so that each character (not byte) becomes 2 characters, for instance:
"Nissim" becomes "N-i-s-s-i-m-"
"01234" becomes ...
|
How should this function be changed to return "123456"?
def f():
s = """123
456"""
return s
UPDATE: Everyone, the question is about understanding ... |
I've read this SO post around the problem to no avail.
I am trying to decompress a .gz file coming from an URL.
url_file_handle=StringIO( gz_data )
gzip_file_handle=gzip.open(url_file_handle,"r")
decompressed_data = gzip_file_handle.read()
gzip_file_handle.close()
... but I get TypeError: ... |
I'm trying to pass a string argument to a target function in a process. Somehow, the string is interpreted as a list of as many arguments as there are characters.
This ... |
I'm aware of using globals(), locals() and getattr to referance things in Python by string (as in this question) but unless I'm missing something obvious I can't seem to use ... |
I am able to properly pass a string variable to the gqlquery through parameter substitution, here's the code i've tried to use;
user_name = self.request.get('username') #retrieved from UI
p = models.UserDetails.all().filter('user_name = ', ...
|
How can I keep help strings in functions to be visible after applying a decorator?
Right now the doc string is (partially) replaced with that of the inner function of the decorator.
def ...
|
i have string stored in python variables, and i am outputting a html that contains javascript, and the i need to create javascript variables.
for ex, in python
title = "What's your name?"
i ... |
I have information about 12340 cars. This info is stored sequentially in two different files:
- car_names.txt, which contains one line for the name of each car
- car_descriptions.txt, which contains the descriptions of each ...
|
If it is environment-independent, what is the theoretical maximum number of characters in a python string?
Also if it differs with version number I'd like to know it for python 2.5.2
|
How can I turn a string such as "+" into the operator plus? Thanks!
|
Python problem: When I am trying to load sth I dumped using cPickle, I get the error message:
ValueError: insecure string pickle
Both the dumping and loading work are done on the same ... |
When I build a c extension using python setup.py build, the result is created under a directory named
build/lib.linux-x86_64-2.6/
where the part after lib. changes by the OS, CPU and Python version.
Is there ... |
I'm using Pylons with Mako templates and I want to avoid typing this all the time:
${ h.some_function_that_outputs_html() | n }
I want to somehow mark the function, or a variable as safe ... |
I have a web application developed in Adobe Flex 3 and Python 2.5 (deployed on Google App Engine). A RESTful web service has been created in Python and its results are ... |
I looking to split a string up with python, I have read the documentation but don't fully understand how to do it, I understand that I need to have some kind ... |
I have this code in Google AppEngine (Python SDK):
from string import maketrans
intab = u"ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ".encode('latin1')
outtab = u"aaaaaaaaaaaaooooooooooooeeeeeeeecciiiiiiiiuuuuuuuuynn".encode('latin1')
logging.info(len(intab))
logging.info(len(outtab))
trantab = maketrans(intab, outtab)
When I run the code in the interactive console ... |
import urllib.request
#name = input("What is your screenname? ");
name = "zezima"
page = urllib.request.urlopen('http://hiscore.runescape.com/index_lite.ws?player=' + name)
page = page.readlines()
skills = []
for line in page:
skills += [line]
print(skills)
Outputs:
[[b'478,2372,1224928266\n'], [b'458,99,59502162\n'], [b'262,99,56673986\n'], [b'1355,99,39565273\n'], [b'227,99,61315106\n'], [b'260,99,37119213\n'], [b'502,99,14155051\n'], ...
|
I have this class:
class STR(str):
def __int__(self):
return 42
If i use it in the promt like this:
>>> a=STR('8')
>>> ord(a)
56
>>> int(a)
42
>>> chr(a)
'*'
that's ... |
Here are the top few lines (all comments) from a python application. What do the first two comment lines indicate? Are they special markers for another app?
# -*- Mode: Python -*-
|
I am on Windows7, using Python 2.6 and wxPython 2.8.10.1. I am trying to get this Open File dialog to work but am running into a weird error. This ... |
I have a C++ application that embeds the Python interpreter. It calls PyImport_Import to load scripts. I need a way of getting any syntax errors as C strings. For example, if ... |
I've looked through python's built in exceptions and the only thing that seems close is ValueError.
from python documentation:
exception ValueError:
Raised when a built-in operation or function receives an ... |
What is the difference or relationship between str and string?
import string
print str
print string
|
I cannot seem to grasp how I would get the strings from a text Ctrl box. I am very new to this, so any help is greatly appricated. Here is the ... |
I have a program which reads commands from a text file
for example, the command syntax will be as follows and is a string
'index command param1 param2 param3'
The number of parameters is ... |