(properties: iterable, immutable)
s = str(42) # convert another data type into a string
s = 'I like you'
s[0] # returns 'I'
len(s) # returns 10
s[:6] # returns 'I like'
s[7:] # returns 'you'
s[-1] # returns 'u'
s.lower() # returns 'i like you'
s.upper() # returns 'I LIKE YOU'
s.startswith('I') # returns True
s.endswith('you') # returns True
s.isdigit() # returns False (returns True if every character in the string is a digit)
s.find('like') # returns index of first occurrence (2), but doesn't support regex
s.find('hate') # returns -1 since not found
s.replace('like','love') # replaces all instances of 'like' with 'love'
s.split(' ') # returns ['I','like','you']
s.split() # same thing
s2 = 'a, an, the'
s2.split(',') # returns ['a',' an',' the']
stooges = ['larry','curly','moe']
' '.join(stooges) # returns 'larry curly moe'
s3 = 'The meaning of life is'
s4 = '42'
s3 + ' ' + s4 # returns 'The meaning of life is 42'
s3 + ' ' + str(42) # same thing
s5 = ' ham and cheese '
s5.strip() # returns 'ham and cheese'
'raining %s and %s' % ('cats','dogs') # old way
'raining {} and {}'.format('cats','dogs') # new way
'raining {arg1} and {arg2}'.format(arg1='cats',arg2='dogs') # named arguments
more examples: http://mkaz.com/2012/10/10/python-string-format/
'pi is {:.2f}'.format(3.14159) # returns 'pi is 3.14'
print 'first line\nsecond line' # normal strings allow for escaped characters
print r'first line\nfirst line' # raw strings treat backslashes as literal characters
i[-3:]
def replace_last(source_string, replace_what, replace_with):
head, sep, tail = source_string.rpartition(replace_what)
return head + replace_with + tail
s = "123123"
r = replace_last(s, '2', 'x')
print r # 1231x3