Strings
How do I use Python's lovely string handling functions?
To split up a string (from Python Wiki):
s = "prefix_stuff"
print s.split('_')[0]
# prefix
>>> ' spacious '.strip()'spacious'>>> 'www.example.com'.strip('cmowz.')'example'
to strip any unwanted characters from a string
Get length of a string:
len('anything')
returns
Add characters to a string:
Using the re (Regular Expressions) module:
import re
if re.search("L_", m):
print "found match! in " + m
#found match! in L_blah
Search and replacing parts of strings is so much nicer than using tokenize:
import re
srcPath = m
match = "L_"
replace = "R_"
resultPath = ""
try:
sourceCaseMatch = re.findall(match, srcPath, re.IGNORECASE)[0]
resultPath = srcPath.replace(sourceCaseMatch, replace)
except:
pass
print "Result: '" + resultPath + "'"
More on the re module
http://docs.python.org/library/re.html#module-contents
Change a string to all upper or lowercase:
Use str.lower() and str.upper().
upperCase = "UPPER"
foo = upperCase.lower()
print foo
bar = foo.upper()
print bar
Convert Back Slashes To Forward Slashes
s.replace('\\', '/')
Using %s in your strings
https://stackoverflow.com/questions/997797/what-does-s-mean-in-a-python-format-string
How can I use an int as a string?
Python declares its variable types on its own, and since it has decided my variable is an int, it will not let me use it as part of a string construction. How to get around this?
Take your pick:
str(someint)
repr(someint)
`someint`
'%d' % someint
(from bytes.com)
string module
Iterating through the alphabet:
import string
foo = string.ascii_uppercase print foo fooo = list(foo) print fooo