- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Common string operations in Python
The string module in Python’s standard library provides following useful constants, classes and a helper function called capwords()
Constants
ascii_letters | The concatenation of lowercase and uppercase constants. |
ascii_lowercase | The lowercase letters 'abcdefghijklmnopqrstuvwxyz' |
ascii_uppercase | The uppercase letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
digits | The string '0123456789'. |
hexdigits | The string '0123456789abcdefABCDEF'. |
octdigits | The string '01234567'. |
punctuation | String of ASCII characters which are considered punctuation characters. |
printable | String of ASCII characters digits, ascii_letters, punctuation, andwhitespace. |
whitespace | A string containing all ASCII characters that are consideredwhitespace such as space, tab, linefeed, return, formfeed, andvertical tab. |
Output
>>> import string >>> string.ascii_letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> string.ascii_lowercase 'abcdefghijklmnopqrstuvwxyz' >>> string.ascii_uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> string.digits '0123456789' >>> string.hexdigits '0123456789abcdefABCDEF' >>> string.octdigits '01234567' >>> string.printable '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~ \t\n\r\x0b\x0c' >>> string.punctuation '!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~' >>> string.whitespace ' \t\n\r\x0b\x0c'
Capwords() function
This function performs following −
Splits the given string argument into words using str.split().
Capitalizes each word using str.capitalize()
and joins the capitalized words using str.join().
Example
>>> text='All animals are equal. Some are more equal' >>> string.capwords(text) 'All Animals Are Equal. Some Are More Equal'
Formatter class
Python’s built-in str class has format() method using which string can be formatted. Formatter object behaves similarly. This may be useful to write customized formatter class by subclassing this Formatter class.
>>> from string import Formatter >>> f=Formatter() >>> f.format('name:{name}, age:{age}, marks:{marks}', name='Rahul', age=30, marks=50) 'name:Rahul, age:30, marks:50'
Template
This class is used to create a string template. It proves useful for simpler string substitutions.
>>> from string import Template >>> text='My name is $name. I am $age years old' >>> t=Template(text) >>> t.substitute(name='Rahul', age=30) 'My name is Rahul. I am 30 years old'
Advertisements