string 3 « 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 3 

1. How to properly add quotes to a string using python?    stackoverflow.com

I want to add a set of (double) quotes to a python string if they are missing but the string can also contain quotes. The purpose of this is to quote all ...

2. How can I get 'urlpatterns = __import__()' to work like a normal import statement?    stackoverflow.com

I'm trying to create an import statement that's pluggable with other projects. This statement is located in urls.py So this works:

from forum.urls import urlpatterns
# Base Class:   <type 'list'>
But this ...

3. instantiate python class from class available as string , only in memory!    stackoverflow.com

I'm using Reportlab to create PDFs. I'm creating two PDFs which I want to merge after I created them. Reportlab provides a way to save a pycanvas (source) (which ...

4. How do you grab a value from the scope from a string    stackoverflow.com

from module import * # adds 'BlahRenderer', 'FooRenderer', 'BarRenderer', etc.
class MyClass
    def __init__(self, value)
        renderer = "%sRenderer" % value
   ...

5. create a tar file in a string using python    stackoverflow.com

I need to generate a tar file but as a string in memory rather than as an actual file. What I have as input is a single filename and a string ...

6. Python, import string of Python code as module    stackoverflow.com

In python you can do something like this to import a module using a string filename, and assign its namespace a variable on the local namespace.

x = __import__(str)
I'm wondering if there ...

7. python: cleaning up a string    stackoverflow.com

i have a string like this

somestring='in this/ string / i have many. interesting.occurrences of {different chars} that need     to .be removed  '
here is the result i ...

8. Why are mutable strings slower than immutable strings?    stackoverflow.com

Why are mutable strings slower than immutable strings? EDIT:

>>> import UserString
... def test():
...     s = UserString.MutableString('Python')
...     for i in range(3):
...     ...

9. Are there existing python modules for dealing with / normalizing units of time represented as strings?    stackoverflow.com

I am new to python and am doing an export and import to a new db. I have a column on my export (to be imported) of strings for units of time, ...

10. Python ctypes - Accessing data string in Structure .value fails    stackoverflow.com

I am able to get a Structure populated as a result of a dll-function (as it seems looking into it using x=buffer(MyData) and then repr(str(buffer(x))) ) But an error is raised if ...

11. Python Titlecase a String with exceptions    stackoverflow.com

Is there a standard way in Python to titlecase a string (i.e. words start with uppercase characters, all remaining cased characters have lowercase) but leaving articles and like lowercased?

12. Python Triple Quoted Strings in Visual Studio 2010    stackoverflow.com

I'm used to using Idle for Python development, but decided to give Visual Studio 2010 + IronPython a try last week. It seems to work fine, but I noticed that ...

13. How would I write some values/strings in particular columns of a file in python    stackoverflow.com

I have some values that I want to write in a text file with the constraint that each value has to go to a particular column of each line. For example, lets ...

14. Concatenate strings read from file with python?    stackoverflow.com

Emacs's auto-fill mode splits the line to make the document look nice. I need to join the strings read from the document. For example, (CR is the carriage return, not the ...

15. Location of python string class in the source code    stackoverflow.com

I'm looking into overloading the '+' operator for a certain string so I was thinking of subclassing the string class then adding the code in the new class. However I ...

16. compress a string in python 3?    stackoverflow.com

I don't understand in 2.X it worked :

import zlib
zlib.compress('Hello, world')
now i have a :
zlib.compress("Hello world!")
TypeError: must be bytes or buffer, not str
How can i compress my string ? Regards Bussiere

17. Getting rid of \x## in strings (Python)    stackoverflow.com

I need to extract a description from a file, which looks like this: "TES4!\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0f\x00\x00\x00HEDR\x0c\x00\xd7\xa3p?h\x03\x00\x00\x00\x08\x00\xffCNAM\t\x00Martigen\x00SNAM\xaf\x00Mart's Mutant Mod - RC4\n\nDiverse creatures & NPCs, new creatures & NPCs, dynamic size and stat scaling, increased spawns, ...

18. combining strings using string substitution - python    stackoverflow.com

hey guys, i want to perform the following operation:

b = 'random'

c = 'stuff'

a  = '%s' + '%s' %(b, c)
but i get the following error:
TypeError: not all arguments converted during string ...

19. What have i done wrong? (python help)    stackoverflow.com

The question i'm working on asks me to "write an expression whose value is the concatenation of the three str values associated with name1 , name2 , and ...

20. Question about python string    stackoverflow.com

i have been asked to write a function which should be called in this way

foo("Hello")
This function also has to return values in this way:
[Hello( user = 'me', answer = 'no', condition ...

21. open a string in notepad at runtime in python    stackoverflow.com

I have a string called 's' and I want to open it in notepad at runtime without saving it in/as a file. Is there any way to achieve this in python? ...

22. How to make a class that acts like a string?    stackoverflow.com

I have a context manager that captures output to a string for a block of code indented under a with statement. This context manager yields a custom result object which will, ...

23. Creating functools.partial *args & *kwargs from parsed strings    stackoverflow.com

I am being passed lists of strings that I would like to convert to method calls using functools.partial:

[ 'object1.method1(arg1, arg2, 4, key=value)', 'object2.method2(6, arg1)' ...]
It's easy to use a regexp to ...

24. Python - About the results retrieved from mysqli    stackoverflow.com

>>> c = conn.cursor()

>>> c.execute('select * from stocks order by price')
>>> for row in c:
...    print row
...

(u'2006-01-05', u'BUY', u'RHAT', 100, 35.14)

(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
As what we can ...

25. Python - Applying Two's Complement to a String    stackoverflow.com

I am trying to add the Two's Complement to a Binary number represented with a string. Assuming the string has already been flipped, how would I go about "adding" 1 to the ...

26. win32com - Write String values in Excel sheet    stackoverflow.com

I'm using win32com to write some dates that I receive from a database, and my problem is that I'm having values like '01' and in Excel is just '1' - not ...

27. Read to right of specific symbol in file from Python    stackoverflow.com

I'm going to separate over 1000 virus signatures and the virus names. I have them all in a text file, and would like to do this with python.

Here is the format:

virus=signature
I ...

28. I'm new to python and having trouble with this looping code    stackoverflow.com

I'm trying to copy sections in a file within a set of XML tags

> <tag>I want to copy the data here</tag>`
  • Please note I found out the data around the tags ...

29. using python to encapsulate part of a string after 3 commas    stackoverflow.com

I am trying to create a python script that adds quotations around part of a string, after 3 commas So if the input data looks like this:

1234,1,1/1/2010,This is a test. One, two, ...

30. Python - A Question on String Editing    stackoverflow.com

I am trying to make a simple text-based game in Python. The idea of which revolves around a deck of playing cards, representing the card face values with A,2,3,4,5,6,7,8,9,10,J,Q, and K ...

31. String error in my python api wrapper class    stackoverflow.com

I'm writing an API wrapper to a couple of different web services. I have a method that has an article url, and I want to extract text from it using alchemyapi.

def extractText(self):
 ...

32. Border around string python    stackoverflow.com

Write a function spaced(s) that outputs spaces and a dashdot border around a string s. The sample code, which calls spaced("Hello") would output:

  --.-.-.-.-
.        ...

33. How do I get a selected string in from a Tkinter text box?    stackoverflow.com

I'd like to be able to get a string out of a highlighted portion of text, how do I go about this?

34. Unpack string with hexadecimals    stackoverflow.com

I have a string that contains a float value in hexadecimal characters like this:

"\\64\\2e\\9b\\38"
I want to extract the float, but in order to do that I have to make Python see ...

35. using a colon in a string in python    stackoverflow.com

i am using python 2.6.5 to develop an app for google app engine - i am not too familiar with python, but i'm learning. i am trying to put a url into ...

36. Strange result in python    stackoverflow.com

Could someone explain me this strange result on python 2.6.6 ?

>>> a = "xx"
>>> b = "xx"
>>> a.__hash__() == b.__hash__()
True
>>> a is b
True # ok.. was just to be sure

>>> a ...

37. How do I write a string equation solver in python?    stackoverflow.com

Thanks in advance! I am writing a program to check if a is true and then return True or False. I need to split it up at the equal sign and ...

38. Lazy logger message string evaluation    stackoverflow.com

I'm using standard python logging module in my python application:

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("log")
while True:
  logger.debug('Stupid log message " + ' '.join([str(i) for i in range(20)]) )
  # Do something
The ...

39. Is this a bug in Python 2.7?    stackoverflow.com

Trying to strip the "0b1" from the left end of a binary number. The following code results in stripping all of binary object. (not good)

>>> bbn = '0b1000101110100010111010001' #converted bin(2**24+**2^24/11)
>>> aan=bbn.lstrip("0b1")  ...

40. Safely evaluate string in Python to call hashlib    stackoverflow.com

I would like to allow people to provide the name of a hash function as a means of digitally fingerprinting some object:

def create_ref(obj, hashfn='sha256'):
    """
    ...

41. How to unescape a query string    stackoverflow.com

I have a query string as follows:

cmd%5Blogin_user%5D%5Busername%5D=dfdsfdsf&cmd%5Blogin_user%5D%5Bpassword%5D=dsfsdf
How do I unescape it in python?

42. String coverage optimization in Python    stackoverflow.com

I have this initial string.

'bananaappleorangestrawberryapplepear'
And also have a tuple with strings:
('apple', 'plepe', 'leoran', 'lemon')
I want a function so that from the initial string and the tuple with strings I obtain this:
'bananaxxxxxxxxxgestrawberryxxxxxxxar'
I ...

43. Best way to iterate through entries delimited by two keywords?    stackoverflow.com

Text File contents:

&CRB  A='test1'   B=123,345, 678   &END
Misc text potentially between entries ...
&CRB  A='test2'   
          ...

44. 'C-style' strings in Python    stackoverflow.com

A very popular question is how to reverse a C-Style string. The C-Style string by definition is a string that is terminated by a null('\0'). Using C(or maybe C++), it is ...

45. How do I set the ident string when using logging.SysLogHandler in Python 2.6?    stackoverflow.com

I have logging configured using logging.fileConfig(). I have a the root logger going to a handler that uses SysLogHandler('/dev/log', handlers.SysLogHandler.LOG_USER) This all works perfectly well, and I see my log entries in ...

46. python how to fetch these string    stackoverflow.com

text=u’<a href="#5" accesskey="5"></a><a href="#1" accesskey="1"><font color="#667755">\ue689</font></a><a href="#2" accesskey="2"><font color="#667755">\ue6ec</font></a><a href="#3" accesskey="3"><font color="#667755">\ue6f6</font></a>ā€˜ 
I am a python new hand. I wanna get \ue6ec?\ue6f6?\ue6ec,how to fetch these string use re module. Thank you very much! ...

47. How to speed up string concatenation in Python?    stackoverflow.com

In the code below concatenation is the bottleneck. As you can see i've tried some sophisticated methods to speed this up, but its bloody slow anyway. I would like to know if ...

48. Modifying strings in Python    stackoverflow.com

I have a string here in python '#b9d9ff'. How do I remove the hash symbol (#)?

49. get data from querystring with python    stackoverflow.com

I have a querystring like a=2&b=3 created by serialize() jQuery. How to get a and b with a Python function?

50. Python delete in a string    stackoverflow.com

I have these 3 string: YELLOW,SMALL,STRETCH,ADULT,T21fdsfdsfs YELLOW,SMALL,STRETCH,ADULT,Tdsfs YELLOW,SMALL,STRETCH,ADULT,TD I would like to remove everything after the last "," including the comma. So i want to remove these parts ",T21fdsfdsfs" ",Tdsfs" and "TD". How could i ...

51. appending a string to another string    stackoverflow.com

I have 2 lists : list1 contains "T" "F" "T" "T" list2 contains "a" "b" "c" "d" I want to create a third list such that I append element1 in list1 to element1 in ...

52. Raise a ValueError    stackoverflow.com

I have this code which find the largest index of a specific character in a string , but I want it to raise a ValueError, when that specific character dose not ...

53. Swig, python and output strings    stackoverflow.com

I am using Swig to wrap a C interface that looks like this:

int dosomething(char **str);
where str is an output string. For example, from C its called like this:
char *str= NULL;
int ...

54. Python Ctypes Null Terminated String Block    stackoverflow.com

I am using a ctypes implementation of CreateProcessWithLogonW, and everything works well except I cannot figure out how to handle this section:

A pointer to an environment block ...

56. python give option if user inputs string    stackoverflow.com

I'm using Python 2.6.6 I have this code:

height = 20
width = 10
x = input('Please insert a number between ' + str(width + 1) + ' and ' + str(height) + ': ')
while ...

57. python about multiple %s in a string    stackoverflow.com

str = 'I love %s and %s, he loves %s and %s.' 
I want to use this format to display I love apple and pitch, he loves apple and pitch. Only add two ...

58. Python: Good way to append to a string    stackoverflow.com

I want an efficient way to append string to another. Is there any good built-in method to use?

59. Python module import by module string name    stackoverflow.com

Possible Duplicate:
How does one do the equivalent of “import * from module” with Python's import function?
I'm trying to dynamically load a python module into ...

60. Google App Engine: LinkProperty to string    stackoverflow.com

An embarrisingly simple question, which makes it all the more frustrating: how do I turn a db.LinkProperty into a string on the google app engine. Suppose I have the following model:

class MyModel(db.Model):
 ...

61. Implementing a custom string method    stackoverflow.com

How do you add a custom method to a built-in python datatype? For example, I'd like to implement one of the solutions from

63. What's the logical value of "string" in Python?    stackoverflow.com

I erroneously wrote this code in Python:

name = input("what is your name?")
if name == "Kamran" or "Samaneh":
    print("That is a nice name")
else:
    print("You have a ...

64. How do you make an identifier out of concatenated strings in Python 3    stackoverflow.com

Basically I want to turn a string in to an identifier for an object like so:

count = 0
for i in range(50):
   count += 1
   functionToMakeIdentifier("foo" + str(count)) ...

65. Get exception description and stack trace which caused an exception, all as a string    stackoverflow.com

I've seen a lot of posts about stack trace and exceptions in Python. But haven't found what I need. I have a chunk of Python 2.7 code that may raise an exception. ...

66. python gnuplot.plot command fails on string input command    stackoverflow.com

in the gnuplot command line you can, for instance, do gnuplot> plot "fileA.dat" using 1:2 title 'data A', \ ...

67. Why MutableString is deprecated in Python?    stackoverflow.com

Why MutableString class is deprecated in Python 2.6 and why it is out of Python 3?

68. Suppose I have a StringIO file. How can I use python-magic to check its file type?    stackoverflow.com

import StringIO
import magic

m = magic.Magic()
thefile = StringIO.StringIO(request.raw_post_data)  # I got this from Django. ajax file uploader.
what now?

69. Python strings references    stackoverflow.com

Possible Duplicate:
Python '==' vs 'is' comparing strings, 'is' fails sometimes, why?
Hi. I have a question about how Python works when it comes how and ...

70. Anybody know a valid mechanism to detect the degree of similarity between a string and its hashcode?    stackoverflow.com

Suppose I hashed a password and obtained a hashcode for it. I need to find the degree of similarity between the password and its hashcode. Please suggest me some different mechanism ...

71. struct.unpack not returning strings    stackoverflow.com

Here is my code (py3.1):

def get_string(self,chars):
    return struct.unpack("{}s".format(chars),self.get_bin(chars))
b'MESH' is going in, (b'MESH',) is coming out. Why am I not getting a string?

72. Python: Code string to shorter meaningless string in reversible way    stackoverflow.com

I'm sorry for the generic question (I don't have any past knowledge about compression and I don't know if it has a possible solution). I have some codes of always 19 characters. These ...

73. How to determine content type of a string    stackoverflow.com

I receive some data as a string. I need to write the data to a file, but the problem is that sometimes the data is compressed/zipped and sometimes it's just ...

74. Python, documentation strings within classes    stackoverflow.com

How do I print documentation strings within classes For functions i can do this:

def func():  
    """
     doc string
    """


print func.__doc__
Is ...

75. Python - Getting access to class instance via module property (by string name)    stackoverflow.com

Ok, let me try and explain this to the best of my ability. Lets say I have a class called Foobar:

class Foobar():
    def __init__(self, foo, bar, choo):
  ...

76. Anybody know a valid mechanism to detect the degree of similarity between two strings    stackoverflow.com

I need to know how far the two strings are similar in terms of some measuring index

77. How do I correctly use Or with strings in an if statement    stackoverflow.com

This is a function I wrote. If I enter Wednesday as the day of the week, the program can't get to it to execute the print code. What is the correct ...

78. Python dynamic instantiation from string name of a class in dynamically imported module    stackoverflow.com

In python, I have to instantiate certain class, knowing its name in a string, but this class 'lives' in a dynamically imported module. An example follows: loader-class script:

import sys
class loader:
  def ...

79. Why is my string not being interpreted correctly in pexpect?    stackoverflow.com

I am currently writing an auto-installation pexpect script. I have been banging my head against the wall on this one. In my pexpect script, I have a process that ...

80. Are there limits to using string.lstrip() in python?    stackoverflow.com

Possible Duplicate:
Is this a bug in Python 2.7?
The .lstrip() function doesn't quite work as I expected on some strings (especially ones with ...

81. python string assigment problem    stackoverflow.com

I have a StringIO object the is filled correctly. I than have the following code:

val = log_fp.getvalue()
lines = val.split('\n') 
newval = ''
for line in lines:
    if (not ...

83. f.read coming up empty    stackoverflow.com

I'm doing all this in the interpreter..

loc1 = '/council/council1'
file1 = open(loc1, 'r')
at this point i can do file1.read() and it prints the file's contents as a string to standard output but if ...

84. python string differences    stackoverflow.com

I am seeing that a string comparison of two identical strings ('fraiser') in Python is failing. When using repr(str1) and repr(str2) I get different results, but I don't know how to ...

85. [python]how to get the size of a string before writing to a file    stackoverflow.com

for example: I get a string: str="please anwser my question", i want to write it to a file. but I need to know the size of the file before writing the ...

86. python class in string    stackoverflow.com

I have name of class in string like:

conf[0] = 'smtp_config'
and i want to run method like:
self.ui.smtp_config.setText("....")
How can i do this in python? :)

87. Use 1 out of 2 returned values as string    stackoverflow.com

divmod(X, Y)
returns (A, B) How would I turn either A or B into a string? EDIT: to clarify, I'd like to use them 1 at a time :)

88. assertionerror returning empty string in python    stackoverflow.com

I am doing this:

try: self.failUnless(sel.is_text_present("F!")) #sel.is_text_present("F!") is false
except AssertionError, e: 
    print("x"+e+"y")
    sys.exit()
it is printing nothing except xy. no class name or anything else. what ...

89. Exposing a C string without copying to python 3.x code    stackoverflow.com

I have a library written with cython that wraps a C library, and i'm exposing a few c strings into python code. Those strings are large, and static (can't deallocate them) ...

90. Strange string concatenation on Python 2.5 in Windows    stackoverflow.com

This code -

for ss_key in sd.keys():
    print str(sd[ss_key]) + ' ' + ss_key
prints the output as expected i.e. converts the int value of ss_key and prints the value ...

91. Python. The coding of a string    stackoverflow.com

>>> word = '\u041a\u041e\u041b'
>>> print u'\u041a\u041e\u041b' 
???
>>> print word 
\u041a\u041e\u041b
How to transform string as a variable to a readable kind (how print word)?

92. How to use a string as stdin    stackoverflow.com

I have been going crazy over a seemingly easy question with Python: I want to call a function that uses raw_input() and input(), and somehow supply those with a string in ...

93. how to store huge strings in python    stackoverflow.com

I have to store huge string of size around 100 million bytes and more.How to handle this in python?

94. How do I build a python string from a ctype struct?    stackoverflow.com

I'm using ctypes and I've defined this struct in order to pass parameters

class my_struct(ctypes.Structure):
    _fields_ = [ ("buffer", ctypes.c_char * BUFSIZE),
        ...

95. applying a filter on a string in python    stackoverflow.com

I have a user typing in his username and I only want valid strings to pass through, meaning only characters in [a-zA-Z0-9]. I am pretty new to python and unsure of ...

96. changing data in a struct in python    stackoverflow.com

I am pretty new in python, and I have a problem I don't know how to solve. For example, I have this struct with members such as administrator, berit, etc:

DEFAULT_DATA = {
'administrator': ...

97. check if string is in abc order    stackoverflow.com

So the function should count the number of times the letters in uppercase are out of abc order.

>>> abc('ABBZHDL')
    2
Above, z and d are out of order.
>>> ...

98. How can I properly send a command to Maya using os.getcwd() in Python    stackoverflow.com

So I'm using sockets to send some output to maya. Unfortunately what I'm getting back from Maya doesn't make sense at all. I'm trying to quote a variable, while escaping the ...

99. Having to evaluate a string to access a class from a module    stackoverflow.com

I've loaded one of my modules <module my_modules.mymodule from .../my_modules/mymodule.pyc> with __import__. Now I'm having the module saved in a variable, but I'd like to create an instance of the class mymodule. ...

100. Python Chosing To Ignore String Value    stackoverflow.com

Using Python v2, is there a way to ignore a value in a string if it is there? For instance: I want someone to enter a value of $100.00, or they could ...

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.