string 1 « string « Python Data Type Q&A

Home
Python Data Type Q&A
1.array
2.date
3.dictionary
4.Format
5.integer
6.List
7.numpy
8.regex
9.string
10.tuple
Python Data Type Q&A » string » string 1 

1. Ignore case in Python strings    stackoverflow.com

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

2. How do I get the name of a python class as a string?    stackoverflow.com

What method do I call to get the name of a class?

3. How do I wrap a string in a file in Python?    stackoverflow.com

How do I create a file-like object (same duck time as File) with the contents of a string?

4. Is there any difference between "string" and 'string' in Python?    stackoverflow.com

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?

5. String Simple Substitution    stackoverflow.com

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

6. Is there a reason Python strings don't have a string length method?    stackoverflow.com

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

7. Python file interface for strings    stackoverflow.com

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

8. how to tell if a string is base64 or not    stackoverflow.com

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

9. How can I repeat a string in Perl?    stackoverflow.com

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?

10. Turn a string into a valid filename in Python    stackoverflow.com

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

11. Newbie Python question about strings with parameters: "%%s"?    stackoverflow.com

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

12. Python: Nicest way to pad zeroes to string    stackoverflow.com

What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length?

13. Read file as string in python    stackoverflow.com

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

14. Capitalize a string    stackoverflow.com

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

15. How to work with very long strings in Python?    stackoverflow.com

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

16. String concatenation vs. string substitution in Python    stackoverflow.com

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

17. Addressing instance name string in __init__(self) in Python    stackoverflow.com

I am doing something like this:

class Class(object):
    def __init__(self):
        self.var=#new instance name string#   
How do I make the __ ...

18. Standard way to embed version into python package?    stackoverflow.com

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

19. is there a string method to capitalize acronyms in python?    stackoverflow.com

This is good:

import string string.capwords("proper name") 'Proper Name' ...

20. How to get the concrete class name as a string in Python    stackoverflow.com

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?

21. Iterating over a String (Python)    stackoverflow.com

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?

22. How do I copy a string to the clipboard on Windows using Python?    stackoverflow.com

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

23. Problems title-casing a string in Python    stackoverflow.com

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)):
  ...

24. Python : is it ok returning both boolean and string?    stackoverflow.com

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

25. Security of Python's eval() on untrusted strings?    stackoverflow.com

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

26. indentation of multiline string    stackoverflow.com

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):
  ...

27. Python comments: # vs strings    stackoverflow.com

I have a question regarding the "standard" way to put comments inside Python source code:

def func():
    "Func doc"
    ... <code>
    'TODO: fix ...

28. Turning ctypes data into python string as quickly as possible    stackoverflow.com

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

29. Does the Python library httplib2 cache URIs with GET strings?    stackoverflow.com

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

30. String inside a string    stackoverflow.com

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

31. Python: Reference to a class from a string?    stackoverflow.com

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):
       ...

32. python write string directly to tarfile    stackoverflow.com

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.

33. Passing a multi-line string as an argument to a script in Windows    stackoverflow.com

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) ...

34. Trimming a string in Python    stackoverflow.com

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

35. Getting Python System Calls as string results    stackoverflow.com

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

36. Case insensitivity in Python strings    stackoverflow.com

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

37. How to bestow string-ness on my class?    stackoverflow.com

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

38. wxPython + multiprocessing: Checking if a color string is legitimate    stackoverflow.com

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

39. Strings and file    stackoverflow.com

Suppose this is my list of languages.

aList = ['Python','C','C++','Java']
How can i write to a file like :
Python      : ...
C        ...

40. filter with string return nothing    stackoverflow.com

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

41. Looking for ways to improve my hangman code    stackoverflow.com

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

42. str.startswith() not working as I intended    stackoverflow.com

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

43. str.startswith() not working as I intended    stackoverflow.com

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

44. How can I get the next string, in alphanumeric ordering, in Python?    stackoverflow.com

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

45. Python display string multiple times    stackoverflow.com

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

46. How can I change a user agent string programmatically?    stackoverflow.com

I would like to write a program that changes my user agent string. How can I do this in Python?

47. How can I change a user agent string programmatically?    stackoverflow.com

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

48. String reversal in Python    stackoverflow.com

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

49. Redirecting console output to a Python string    stackoverflow.com

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

50. How do I test if a string exists in a Genshi stream?    stackoverflow.com

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

51. Lookup and combine data in Python    stackoverflow.com

I have 3 text files

  1. many lines of value1<tab>value2 (maybe 600)
  2. many more lines of value2<tab>value3 (maybe 1000)
  3. many more lines of value2<tab>value4 (maybe 2000)
Not all lines match, some will have one or more ...

52. Running Python code contained in a string    stackoverflow.com

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

53. Python behavior of string in loop    stackoverflow.com

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

54. How to append two strings in Python?    stackoverflow.com

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

55. Simplifying Data with a for loop (Python)    stackoverflow.com

I was trying to simplify the code:

            header = []
           ...

56. A question regarding string instance uniqueness in python    stackoverflow.com

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

57. Python: access class property from string    stackoverflow.com

I have a class like the following:

class User:
    def __init__(self):
        self.data = []
        self.other_data ...

58. Static vs instance methods of str in Python    stackoverflow.com

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

59. How to create a property with its name in a string?    stackoverflow.com

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_ ...

60. What does % do to strings in Python?    stackoverflow.com

I have failed to find documentation for the operator % as it is used on strings in Python. Does someone know where that documentation is?

61. string quoting issues in doctests    stackoverflow.com

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': ...

62. How to read String in java that was written using python's struct.pack method    stackoverflow.com

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

63. cutdown uuid further to make short string    stackoverflow.com

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

64. If I have the contents of a zipfile in a Python string, can I decompress it without writing it to a file?    stackoverflow.com

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

65. What is the most efficient string concatenation method in python?    stackoverflow.com

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

66. One-liner Python code for setting string to 0 string if empty    stackoverflow.com

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

67. Python (Imaging library): Resample string as argument    stackoverflow.com

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

68. Python : Revert to base __str__ behavior    stackoverflow.com

How can I revert back to the default function that python uses if there is no __str__ method?

class A :
   def __str__(self) :
      return ...

69. Google App Engine - Request class query_string    stackoverflow.com

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

70. In Python, what is the best way to execute a local Linux command stored in a string?    stackoverflow.com

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

71. emacs 23 hangs on python mode when typing string block """    stackoverflow.com

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

72. python serialize string    stackoverflow.com

I am needing to unserialize a string into an array in python just like php and then serialize it back.

73. Feeding a string into Popen    stackoverflow.com

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

74. get every combination of strings    stackoverflow.com

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

75. fast string modification in python    stackoverflow.com

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

76. How does Python's triple-quote string work?    stackoverflow.com

How should this function be changed to return "123456"?

def f():
    s = """123
    456"""
    return s
UPDATE: Everyone, the question is about understanding ...

77. Python gzip: is there a way to decompress from a string?    stackoverflow.com

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

78. String arguments in python multiprocessing    stackoverflow.com

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

79. Calling types via their name as a string in Python    stackoverflow.com

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

80. Unable to get results when passing a string via parameter substitution in gql query    stackoverflow.com

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 = ', ...

81. How to keep help strings the same when applying decorators?    stackoverflow.com

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

82. generating javascript string in python    stackoverflow.com

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

83. Process two files at the same time in Python    stackoverflow.com

I have information about 12340 cars. This info is stored sequentially in two different files:

  1. car_names.txt, which contains one line for the name of each car
  2. car_descriptions.txt, which contains the descriptions of each ...

84. What is the max length of a python string?    stackoverflow.com

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

85. Python:: Turn string into operator    stackoverflow.com

How can I turn a string such as "+" into the operator plus? Thanks!

86. Python ValueError: insecure string pickle    stackoverflow.com

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

87. How to get the arch string that distutils uses for builds?    stackoverflow.com

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

88. Mark string as safe in Mako    stackoverflow.com

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

89. Uncompress Zlib string in using ByteArrays    stackoverflow.com

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

90. Python Spliting a string    stackoverflow.com

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

91. Python's string.maketrans works at home but fails on Google App Engine    stackoverflow.com

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

92. Strings are wrapped in b'...'    stackoverflow.com

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

93. How to override ord behaivour in Python for str childs?    stackoverflow.com

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

94. What is the use of strings like "-*- Mode: Python -*-" found at the top of some python files?    stackoverflow.com

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

95. wxPython file dialog error: missing "|" in the wildcard string!    stackoverflow.com

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

96. How to get Python error as C string?    stackoverflow.com

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

97. python: Should I use ValueError or create my own subclass to handle invalid strings?    stackoverflow.com

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

98. Relationship between string module and str    stackoverflow.com

What is the difference or relationship between str and string?

import string 
print str
print string 

99. Getting String from A TextCtrl Box    stackoverflow.com

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

100. Help with Python strings    stackoverflow.com

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

java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.