View Category

Output a string to the console

Write the string "Hello World!" to STDOUT
python
print "Hello World!"
# python 3 requires parentheses for print

print('Hello, world!\n')

Retrieve a string containing ampersands from the variables in a url

My PHP script first does a query to obtain customer info for a form. The form has first name and last name fields among others. The customer has put entries such as "Ron & Jean" in the first name field in the database. Then the edit form script is called with variables such as

"http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith".

The script variable for first name $_REQUEST['firstname'] never gets beyond the "Ron" value because of the ampersand in the data.

I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like "http://myserver/custinfo/edit.php?mode=view&fname="Ronxxnbsp;xxamp;xxnbsp;Jean"&lname=SMITH". (sorry I had to add the xx to replace the ampersand or it didn't display meaningful url contents the browser sees.)

Of course this fails for the same reasons. What is a better approach?
python
# I'm not really sure this is what the site is for,
# but the one unsolved problem for python was grating me.
# Anyway, I think this is what you're looking for.

from urllib import urlencode

query_dict = {'mode': 'view',
'fname': 'Ron & Jean',
'lname': 'Smith'}

print urlencode(query_dict.items())

# Which will be 'lname=Smith&mode=view&fname=Ron+%26+Jean'.

string-wrap

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> "

Expected output:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t
> he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox
> jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui
> ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy
> dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o
> ver the lazy dog. The quick brown fox jumps over the lazy dog.
python
def wrap(string, length):

while len(string):
print("> " + string[0:length - 1])
string = string[length - 1:].strip()


wrap("The quick brown fox jumps over the lazy dog. " * 10, 78)

Define a string containing special characters

Define the literal string "\#{'}${"}/"
python
# yes, Python has way too many forms of string literals :)
print "\\#{'}${\"}/"
print "\\#{'}${"'"'"}/"
print r"""\#{'}${"}/"""
print '\\#{\'}${"}/'
print '\\#{'"'"'}${"}/'
print r'''\#{'}${"}/'''

Define a multiline string

Define the string:
"This
Is
A
Multiline
String"
python
text = """This
Is
A
Multiline
String"""
# with proper indentation
text = (
"This\n"
"Is\n"
"A\n"
"Multiline\n"
"String"
)

Define a string containing variables and expressions

Given variables a=3 and b=4 output "3+4=7"
python
class EvalDict(dict):
def __getitem__(s, k):
return eval(k, s)

a=3; b=4
"%(a)d+%(b)d=%(a+b)d" % EvalDict(locals())
a=3; b=4
"%d+%d=%d" % (a, b, a+b)

Reverse the characters in a string

Given the string "reverse me", produce the string "em esrever"
python
"reverse me"[::-1]

Reverse the words in a string

Given the string "This is a end, my only friend!", produce the string "friend! only my end, the is This"
python
' '.join(reversed("This is a end, my only friend!".split()))

Text wrapping

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> ", yielding this result:

> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
python
import textwrap
print textwrap.fill("The quick brown fox jumps over the lazy dog. " * 10,
72, initial_indent="> ", subsequent_indent="> ")

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello".
python
assert 'hello' == ' hello '.strip()

Simple substitution cipher

Take a string and return the ROT13 and ROT47 (Check Wikipedia) version of the string.
For example:
String is: Hello World #123
ROT13 returns: Uryyb Jbeyq #123
ROT47 returns: w6==@ (@C=5 R`ab
python
# rot13, readable
rot13_tbl = string.maketrans("ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz", "NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm")
string.translate("Hello World #123", rot13_tbl)


#
# "a bad programmer can write bad code in any language"
#

# rot13, "clever"
string.translate("Hello World #123", string.maketrans(string.lowercase+string.uppercase, string.lowercase[13:]+string.lowercase[:13]+string.uppercase[13:]+string.uppercase[:13]))

# rot47, very "clever"
''.join([ord(c) in range(33,127) and chr(((ord(c)-33+47)%(127-33))+33) or c for c in "Hello World #123"])

"Hello World #123".encode('rot13')

Make a string uppercase

Transform "Space Monkey" into "SPACE MONKEY"
python
"Space Monkey".upper()

Make a string lowercase

Transform "Caps ARE overRated" into "caps are overrated"
python
"Caps ARE overRated".lower()

Capitalise the first letter of each word

Transform "man OF stEEL" into "Man Of Steel"
python
from string import capwords
capwords("man OF stEEL")
' '.join(s.capitalize() for s in "man OF stEEL".split())
"man OF stEEL".title()