GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing pythonadventures.wordpress.com — stringbuilder – Python Adventures Python AdventuresWelcome to the Jungle!
Archive
Posts Tagged ‘stringbuilder’
StringBuilder functionality in PythonProblem You need to concatenate lots of string elements. Under Java we use a StringBuilder for this, but how to do that in Python? Solution #1 Use a list, and join the elements of the list at the end. This is much more efficient than concatenating strings since strings are immutable objects, thus if you concatenate a string with another, the result is a NEW string object (the problem is the same with Java strings). Example: def g():
sb = []
for i in range(30):
sb.append("abcdefg"[i%7])
return ''.join(sb)
print g() # abcdefgabcdefgabcdefgabcdefgab
Solution #2 (update 20120110) Use a StringIO object and print to it. In short: from cStringIO import StringIO out = StringIO() print >>out, 'arbitrary text' # 'out' behaves like a file return out.getvalue()
Categories: python
Tags: concatenate, java, string, stringbuffer, stringbuilder, StringIO
Blog Stats
Random PostRecent Postsascii
bash
beautifulsoup
book
bpython
challenge
command-line
convert
cron
crontab
date
datetime
distance
dropbox
email
eric
exercise
extract
file
firefox
github
google
hacking
heroku
html
ide
imdb
imgur
install
ipython
java
jinja2
json
linux
module
modules
MongoDB
movies
news
pdf
perl
pi
pip
print
pylint
pypi
python3
python shell
quote
readline
reddit
redirect
refactoring
regexp
requests
reverse
review
shell
sound
stdout
string
tab
text
threads
time
tip
tutorial
unicode
url
video
virtualenv
virtual environment
virtualenvwrapper
xml
zip Archives
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Cookie Policy
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |