Python
- String Methods
In addition to expression operators, string provides a set of method that implements more sophisticated text-processing methods.
Methods are functions that are associated with particular objects. Actually, they are attributes attached to objects. In general, expressions and built-in functions work across a range of types. But methods are specific to object types, in this case, strings.
The method call expression object.method(arguments) is evaluated from left to right. Python will fetch the method of the object and then call it passing in the arguments.
Following is the summary of the method.
We'll use a sample string:
s = 'Black holes are where God divided by zero' s2 = 'sample.txt'
- capitalize( )
Return a copy of the string with only its first character capitalized. For 8-bit strings, this method is locale-dependent.>>> s.capitalize() 'Black holes are where god divided by zero'
- center( width[, fillchar])
Return centered in a string of length width. Padding is done using the specified fillchar (default is a space).>>> s.center(50,'*') '****Black holes are where God divided by zero*****'
- count( sub[, start[, end]])
Return the number of occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.>>> s.count('i') 2 >>> s.count('hole') 1 >>> map(s.count, s) [1, 2, 2, 1, 1, 7, 2, 3, 2, 6, 1, 7, 2, 3, 6, 7, 1, 2, 6, 3, 6, 7, 1, 3, 4, 7, 4, 2, 1, 2, 4, 6, 4, 7, 1, 1, 7, 1, 6, 3, 3]
- decode( [encoding[, errors]])
Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding. errors may be given to set a different error handling scheme. The default is 'strict', meaning that encoding errors raise UnicodeError. Other possible values are 'ignore', 'replace' and any other name registered via codecs.register_error.>>> s.decode() u'Black holes are where God divided by zero'
- encode( [encoding[,errors]])
Return an encoded version of the string. Default encoding is the current default string encoding. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace'. - endswith( suffix[, start[, end]])
Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.>>> s.endswith('txt') False >>> s2.endswith('txt') True
- expandtabs( [tabsize])
Return a copy of the string where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. - find(sub[, start[, end]])
Return the lowest index in the string where substring sub is found, such that sub is contained in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.>>> S = 'aaaaaSPYbbbbSPYcccc' >>> where = S.find('SPY') >>> where 5 >>> S = S[:where] + 'SKY' + S[(where+3):] >>> S 'aaaaaSKYbbbbSPYcccc'
- index( sub[, start[, end]])
Like find(), but raise ValueError when the substring is not found.>>> s.index('where') 16 >>> s.index('one') Traceback (most recent call last): File "
", line 1, in ValueError: substring not found >>> s.find('one') -1 - isalnum( )
Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise. For 8-bit strings, this method is locale-dependent.>>> 'abc123'.isalnum() True >>> 'abcdef'.isalnum() True >>> 'abc def'.isalnum() False
- isalpha( )
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. For 8-bit strings, this method is locale-dependent.>>> 'abc'.isalpha() True >>> 'abc7'.isalpha() False
- isdigit( )
Return true if all characters in the string are digits and there is at least one character, false otherwise. For 8-bit strings, this method is locale-dependent.>>> '123'.isdigit() True >>> '123a'.isdigit() False
- islower( )
Return true if all cased characters in the string are lowercase and there is at least one cased character, false otherwise. For 8-bit strings, this method is locale-dependent. - isspace( )
Return true if there are only whitespace characters in the string and there is at least one character, false otherwise. For 8-bit strings, this method is locale-dependent.>>> '1 f'.isspace() False >>> ' '.isspace() True
- istitle( )
Return true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return false otherwise. For 8-bit strings, this method is locale-dependent.>>> 'Black holes'.istitle() False >>> 'Black Holes'.istitle() True
- isupper( )
Return true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise. For 8-bit strings, this method is locale-dependent. - join( seq)
Return a string which is the concatenation of the strings in the sequence seq. The separator between elements is the string providing this method.>>> seq = ['a','b','c','d'] >>> print ''.join(seq) abcd >>> print '-'.join(seq) a-b-c-d >>> >>> ''.join([`x` for x in xrange(101)]) '0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100' >>>
- ljust( width[, fillchar])
Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s).>>> '123'.ljust(10) '123 '
- lower( )
Return a copy of the string converted to lowercase. For 8-bit strings, this method is locale-dependent. - lstrip( [chars])
Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped:>>> ' too much left side space '.lstrip() 'too much left side space ' >>> 'www.bogotobogo.com'.lstrip('w.') 'bogotobogo.com'
- partition( sep)
Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.>>> s.partition('are') ('Black holes ', 'are', ' where God divided by zero')
- replace( old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.>>> S = 'beetles' >>> S = S[:3] + 'xx' + S[5:] >>> S 'beexxes' >>> S = 'beetles' >>> S = S.replace('ee','xx') >>> S 'bxxtles'
- rfind( sub [,start [,end]])
Return the highest index in the string where substring sub is found, such that sub is contained within s[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.>>> s 'Black holes are where God divided by zero' >>> s.rfind(' ') 36
- rindex( sub[, start[, end]])
Like rfind() but raises ValueError when the substring sub is not found. - rjust( width[, fillchar])
Return the string right justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s).>>> '123'.rjust(10) ' 123'
- rpartition( sep)
Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself. - rsplit( [sep [,maxsplit]])
Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any whitespace string is a separator. Except for splitting from the right, rsplit() behaves like split() which is described in detail below. - rstrip( [chars])
Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped:>>> ' too much right side space '.rstrip() ' too much right side space' >>> 'mississippi'.rstrip('im') 'mississipp' >>> 'mississippi'.rstrip('ip') 'mississ'
- split( [sep [,maxsplit]])
Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. (thus, the list will have at most maxsplit+1 element).
If maxsplit is not specified, then there is no limit on the number of splits (all possible splits are made). Consecutive delimiters are not grouped together and are deemed to delimit empty strings:>>> '1,,2'.split(',') ['1', '', '2']
The sep argument may consist of multiple characters>>> '1, 2, 3'.split(', ') ['1', '2', '3']
Splitting an empty string with a specified separator returns>>> ' '.split() []
If sep is not specified or is None, a different splitting algorithm is applied. First, whitespace characters (spaces, tabs, newlines, returns, and formfeeds) are stripped from both ends. Then, words are separated by arbitrary length strings of whitespace characters. Consecutive whitespace delimiters are treated as a single delimiter>>> '1 2 3'.split() ['1', '2', '3']
Splitting an empty string or a string consisting of just whitespace returns an empty list.To split a string with multiple delimiters, we can use re:
import re # split with semicolon, comma, space >>> str = 'Life; a walking, shadow' >>> str1 = re.split(';|,| ', str) >>> str1 ['Life', '', 'a', 'walking', '', 'shadow'] >>> # split with semicolon+space, comma+space, space >>> str2 = re.split('; |, | ',str) >>> str2 ['Life', 'a', 'walking', 'shadow']
- splitlines( [keepends])
Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. - startswith( prefix[, start[, end]])
Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position. - strip( [chars])
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed.
If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:>>> ' too much space '.strip() 'too much space' >>> 'www.bogotobogo.com'.strip('.wmoc') 'bogotobog' >>>
- swapcase( )
Return a copy of the string with uppercase characters converted to lowercase and vice versa. For 8-bit strings, this method is locale-dependent. - title( )
Return a titlecased version of the string: words start with uppercase characters, all remaining cased characters are lowercase. For 8-bit strings, this method is locale-dependent. - translate( table[, deletechars])
Return a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256.
We can use the maketrans() helper function in the string module to create a translation table.
For Unicode objects, the translate() method does not accept the optional deletechars argument. Instead, it returns a copy of the s where all characters have been mapped through the given translation table which must be a mapping of Unicode ordinals to Unicode ordinals, Unicode strings or None.
Unmapped characters are left untouched.
Characters mapped to None are deleted. - upper( )
Return a copy of the string converted to uppercase. For 8-bit strings, this method is locale-dependent. - zfill(width)
Return the numeric string left filled with zeros in a string of length width. The original string is returned if width is less than len(s).
Python tutorial
Python Home
Introduction
Running Python Programs (os, sys, import)
Modules and IDLE (Import, Reload, exec)
Object Types - Numbers, Strings, and None
Strings - Escape Sequence, Raw String, and Slicing
Strings - Methods
Formatting Strings - expressions and method calls
Files and os.path
Traversing directories recursively
Subprocess Module
Regular Expressions with Python
Regular Expressions Cheat Sheet
Object Types - Lists
Object Types - Dictionaries and Tuples
Functions def, *args, **kargs
Functions lambda
Built-in Functions
map, filter, and reduce
Decorators
List Comprehension
Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism
Hashing (Hash tables and hashlib)
Dictionary Comprehension with zip
The yield keyword
Generator Functions and Expressions
generator.send() method
Iterators
Classes and Instances (__init__, __call__, etc.)
if__name__ == '__main__'
argparse
Exceptions
@static method vs class method
Private attributes and private methods
bits, bytes, bitstring, and constBitStream
json.dump(s) and json.load(s)
Python Object Serialization - pickle and json
Python Object Serialization - yaml and json
Priority queue and heap queue data structure
Graph data structure
Dijkstra's shortest path algorithm
Prim's spanning tree algorithm
Closure
Functional programming in Python
Remote running a local file using ssh
SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table
SQLite 3 - B. Selecting, updating and deleting data
MongoDB with PyMongo I - Installing MongoDB ...
Python HTTP Web Services - urllib, httplib2
Web scraping with Selenium for checking domain availability
REST API : Http Requests for Humans with Flask
Blog app with Tornado
Multithreading ...
Python Network Programming I - Basic Server / Client : A Basics
Python Network Programming I - Basic Server / Client : B File Transfer
Python Network Programming II - Chat Server / Client
Python Network Programming III - Echo Server using socketserver network framework
Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn
Python Coding Questions I
Python Coding Questions II
Python Coding Questions III
Python Coding Questions IV
Python Coding Questions V
Python Coding Questions VI
Python Coding Questions VII
Python Coding Questions VIII
Python Coding Questions IX
Python Coding Questions X
Image processing with Python image library Pillow
Python and C++ with SIP
PyDev with Eclipse
Matplotlib
Redis with Python
NumPy array basics A
NumPy Matrix and Linear Algebra
Pandas with NumPy and Matplotlib
Celluar Automata
Batch gradient descent algorithm
Longest Common Substring Algorithm
Python Unit Test - TDD using unittest.TestCase class
Simple tool - Google page ranking by keywords
Google App Hello World
Google App webapp2 and WSGI
Uploading Google App Hello World
Python 2 vs Python 3
virtualenv and virtualenvwrapper
Uploading a big file to AWS S3 using boto module
Scheduled stopping and starting an AWS instance
Cloudera CDH5 - Scheduled stopping and starting services
Removing Cloud Files - Rackspace API with curl and subprocess
Checking if a process is running/hanging and stop/run a scheduled task on Windows
Apache Spark 1.3 with PySpark (Spark Python API) Shell
Apache Spark 1.2 Streaming
bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...
Flask app with Apache WSGI on Ubuntu14/CentOS7 ...
Fabric - streamlining the use of SSH for application deployment
Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App
Neural Networks with backpropagation for XOR using one hidden layer
NLP - NLTK (Natural Language Toolkit) ...
RabbitMQ(Message broker server) and Celery(Task queue) ...
OpenCV3 and Matplotlib ...
Simple tool - Concatenating slides using FFmpeg ...
iPython - Signal Processing with NumPy
iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github
iPython and Jupyter Notebook with Embedded D3.js
Downloading YouTube videos using youtube-dl embedded with Python
Machine Learning : scikit-learn ...
Django 1.6/1.8 Web Framework ...
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization