You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
translate() to perform the string mapping based on translation table
the first argument to maketrans() is string characters to be replaced, the second is characters to replace with and the third is characters to be mapped to None
>>>greeting='===== Have a great day ====='>>>greeting.translate(str.maketrans('=', '-'))
'----- Have a great day -----'>>>greeting='===== Have a great day!! ====='>>>greeting.translate(str.maketrans('=', '-', '!'))
'----- Have a great day -----'>>>importstring>>>quote='SIMPLICITY IS THE ULTIMATE SOPHISTICATION'>>>tr_table=str.maketrans(string.ascii_uppercase, string.ascii_lowercase)
>>>quote.translate(tr_table)
'simplicity is the ultimate sophistication'>>>sentence="Thi1s is34 a senten6ce">>>sentence.translate(str.maketrans('', '', string.digits))
'This is a sentence'>>>greeting.translate(str.maketrans('', '', string.punctuation))
' Have a great day '
removing leading/trailing/both characters
only consecutive characters from start/end string are removed
by default whitespace characters are stripped
if more than one character is specified, it is treated as a set and all combinations of it are used
>>>greeting=' Have a nice day :) '>>>greeting.strip()
'Have a nice day :)'>>>greeting.rstrip()
' Have a nice day :)'>>>greeting.lstrip()
'Have a nice day :) '>>>greeting.strip(') :')
'Have a nice day'>>>greeting='===== Have a great day!! ====='>>>greeting.strip('=')
' Have a great day!! '
styling
width argument specifies total output string length
>>>' Hello World '.center(40, '*')
'************* Hello World **************'
changing case and case checking
>>>sentence='thIs iS a saMple StrIng'>>>sentence.capitalize()
'This is a sample string'>>>sentence.title()
'This Is A Sample String'>>>sentence.lower()
'this is a sample string'>>>sentence.upper()
'THIS IS A SAMPLE STRING'>>>sentence.swapcase()
'THiS Is A SAmPLE sTRiNG'>>>'good'.islower()
True>>>'good'.isupper()
False
>>>sentence='This is a sample string'>>>'is'insentenceTrue>>>'this'insentenceFalse>>>'This'insentenceTrue>>>'this'insentence.lower()
True>>>'is a'insentenceTrue>>>'test'notinsentenceTrue
get number of times character sequence is present (non-overlapping)
>>>sentence='This is a sample string'>>>sentence.count('is')
2>>>sentence.count('w')
0>>>word='phototonic'>>>word.count('oto')
1
matching character sequence at start/end of string
>>>sentence'This is a sample string'>>>sentence.startswith('This')
True>>>sentence.startswith('The')
False>>>sentence.endswith('ing')
True>>>sentence.endswith('ly')
False
split string based on character sequence
returns a list
to split using regular expressions, use re.split() instead
>>>sentence='This is a sample string'>>>sentence.split()
['This', 'is', 'a', 'sample', 'string']
>>>"oranges:5".split(':')
['oranges', '5']
>>>"oranges :: 5".split(' :: ')
['oranges', '5']
>>>"a e i o u".split(' ', maxsplit=1)
['a', 'e i o u']
>>>"a e i o u".split(' ', maxsplit=2)
['a', 'e', 'i o u']
>>>line='{1.0 2.0 3.0}'>>>nums= [float(s) forsinline.strip('{}').split()]
>>>nums
[1.0, 2.0, 3.0]
joining list of strings
>>>str_list
['This', 'is', 'a', 'sample', 'string']
>>>' '.join(str_list)
'This is a sample string'>>>'-'.join(str_list)
'This-is-a-sample-string'>>>c=' :: '>>>c.join(str_list)
'This :: is :: a :: sample :: string'
replace characters
third argument specifies how many times replace has to be performed
variable has to be explicitly re-assigned to change its value
>>>phrase='2 be or not 2 be'>>>phrase.replace('2', 'to')
'to be or not to be'>>>phrase'2 be or not 2 be'>>>phrase.replace('2', 'to', 1)
'to be or not 2 be'>>>phrase=phrase.replace('2', 'to')
>>>phrase'to be or not to be'
>>>quote="So many books, so little time">>>re.search(r'([a-z]{2,}).*\1', quote, re.I)
<_sre.SRE_Matchobject; span=(0, 17), match='So many books, so'>>>>re.search(r'([a-z])\1', quote, re.I)
<_sre.SRE_Matchobject; span=(9, 11), match='oo'>>>>re.findall(r'([a-z])\1', quote, re.I)
['o', 't']
Search and Replace
Syntax
re.sub(pattern, repl, string, count=0, flags=0)
simple substitutions
re.sub will not change value of variable passed to it, has to be explicity assigned
>>>sentence='This is a sample string'>>>re.sub('sample', 'test', sentence)
'This is a test string'>>>sentence'This is a sample string'>>>sentence=re.sub('sample', 'test', sentence)
>>>sentence'This is a test string'>>>re.sub('/', '-', '25/06/2016')
'25-06-2016'>>>re.sub('/', '-', '25/06/2016', count=1)
'25-06/2016'>>>greeting='***** Have a great day *****'>>>re.sub('\*', '=', greeting)
'===== Have a great day ====='
backreferencing
>>>words='night and day'>>>re.sub(r'(\w+)( \w+ )(\w+)', r'\3\2\1', words)
'day and night'>>>line='Can you spot the the mistakes? I i seem to not'>>>re.sub(r'\b(\w+) \1\b', r'\1', line, flags=re.I)
'Can you spot the mistakes? I seem to not'