RSS

Monthly Archives: May 2013

Some Python String Manipulation Functions (Quick Reference)

Just putting some python string manipulation techniques in a place as quick reference

Suppose

a = “a quick brown fox run over the lazy dog”

 

reverse string

a[::-1]

 

last character of the string

a[-1:]

 

first 4 character of the string

a[:4]

 

split a string with white spaces

a.split()

 

split a string with character or string (not regular expression)

a.split(‘fox’)

 

find a string inside a string

a.find(‘run’)

a.find(‘run’,0)

a.find(‘run’,0,len(a))

 

find from end of the string

a.rfind(‘run’)

a.rfind(‘run’,0)

a.rfind(‘run’,0,len(a))

 

count number of occurrence in a string

a.count(‘a’)

 

join several string together with separators

st = “,”

seq = (“cat”, “tiger”, “lion”)

print st.join( seq )

 

change the case into opposite one, if lower go to upper, if upper go lower.

a. swapcase()

 

replace part of the string

a.replace(‘run’,’walk’)

 

 

left, right and center justify

a.ljust(10,’’)

a.rjust(10,’ ’)

a.center(10,’ ‘)

 
1 Comment

Posted by on May 4, 2013 in Programming, Python