Python string Introduction














































Python string Introduction



INTRODUCTION TO PYTHON STRING MODULE


In Python, Strings are arrays of bytes representing Unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1.

The string module contains a number of useful constants and classes, as well as some deprecated legacy functions that are also available as methods on strings.

How to use :

It's a built-in module and we have to import it before using any of its constants and classes.
import string

String Constants :
The constants defined in this module are:

string.ascii_letters
The concatenation of the ascii_lowercase and ascii_uppercase . This value is not locale-dependent.

string.ascii_lowercase
The lowercase letters 'abcdefghijklmnopqrstuvwxyz'. This value is not locale-dependent and will not change.

string.ascii_uppercase
The uppercase letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. This value is not locale-dependent and will not change.

string.digits
The string '0123456789'.

string.hexdigits
The string '0123456789abcdefABCDEF'.

string.octdigits
The string '01234567'.

string.punctuation
String of ASCII characters which are considered punctuation characters in the C locale: !"#$%&'()*+,-./:;<=>?@[]^_`{|}~.

string.printable
String of ASCII characters which are considered printable. This is a combination of digitsascii_letterspunctuation, and whitespace.

string.whitespace
A string containing all ASCII characters that are considered whitespace. This includes the characters space, tab, linefeed, return, formfeed, and vertical tab.

Here is the use of constants:


String module classes :


Python string module contains two classes  Formatter and Template.

Formatter :-

It behaves exactly same as str.format() function. This class become useful if you want to subclass it and define your own format string syntax.


Let's look at a simple example of using Formatter class.

from string import Formatter

formatter = Formatter()

print(formatter.format('{} {website}''Welcome to'website='cppsecrets'))

# format() behaves in similar manner
print('{} {website}'.format('Welcome to'website='cppsecrets'))

Output:

Welcome to cppsecrets
Welcome to cppsecrets


Template :-

This class is used to create a string template for simpler string substitutions . It's useful in implementing internationalization (i18n) in an application where we don't need complex formatting rules.

from string import Template

t = Template('  is working in ')
s = t.substitute(name='Vishal'company='cppsecrets')
print(s)

Output: Vishal is working in cppsecrets.



String built-in methods :


In Python 1.6 and later, most string operations are made available as string methods as well, and many functions in the string module are simply wrapper functions that call the corresponding string method.


Python includes the following built-in methods to manipulate strings.


Sr.No.Methods & Description
1 capitalize()

Capitalizes first letter of string

2center()

Returns a string padded with fillchar with the original string centered to a total of width columns.

3count()

Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.

4isidentifier()

The isidentifier() method returns True if the string is a valid identifier in Python. If not, it returns False.

5encode()

Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'.

6endswith()

Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.

7expandtabs()

Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.

8find()

Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.

9index()

Same as find(), but raises an exception if str not found.

10isalnum()

Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.

11isalpha()

Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.

12isdigit()

Returns true if string contains only digits and false otherwise.

13islower()

Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.

14isnumeric()

Returns true if a unicode string contains only numeric characters and false otherwise.

15isspace()

Returns true if string contains only whitespace characters and false otherwise.

16istitle()

Returns true if string is properly "titlecased" and false otherwise.

17isupper()

Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.

18join()

Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.

19len()

Returns the length of the string

20ljust()

Returns a space-padded string with the original string left-justified to a total of width columns.

21lower()

Converts all uppercase letters in string to lowercase.

22lstrip()

Removes all leading whitespace in string.

23maketrans()

Returns a translation table to be used in translate function.

24max()

Returns the max alphabetical character from the string str.

25min()

Returns the min alphabetical character from the string str.

26replace()

Replaces all occurrences of old in string with new or at most max occurrences if max given.

27rfind()

Same as find(), but search backwards in string.

28rindex()

Same as index(), but search backwards in string.

29rjust()

Returns a space-padded string with the original string right-justified to a total of width columns.

30rstrip()

Removes all trailing whitespace of string.

31split()

Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given.

32splitelines()

Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.

33startswith()

Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise.

34strip()

Performs both lstrip() and rstrip() on string

35swapcase()

Inverts case for all letters in string.

36title()

Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.

37translate()

Translates string according to translation table str(256 chars), removing those in the del string.

38upper()

Converts lowercase letters in string to uppercase.

39zfill()

Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).

40isdecimal()

Returns true if a unicode string contains only decimal characters and false otherwise.

41                              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.
42rpartition(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.


43                       rsplit()

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.

44format()

The string format() method formats the given string into a nicer output in Python.

45
isprintable()
 Returns true if all characters in the string are printable.

46     casefold()

Translates string according to translation table str(256 chars), removing those in the del string.

47format_map()

The format_map() method is similar to str.format(**mapping) except that str.format(**mapping) creates a new dictionary whereas str.format_map(mapping) doesn't.



Therefore,we can see that string module provides additional tools to manipulate strings. 
All these above functions helps us to manipulate several many operations on strings.


       *********END OF ARTICLE***********



More Articles of Vishal Lodhi:

Name Views Likes
Python string zfill 114 0
Python string swapcase 92 0
Python string title 97 0
Python string startswith 103 0
Python string replace 144 0
Python string translate 85 0
Python string rpartition 85 0
Python string partition 74 0
Python string splitlines 114 0
Python string rsplit 79 0
Python string split 76 0
Python string rindex 82 0
Python string rfind 106 0
Python string upper 80 0
Python string lower 81 0
Python string maketrans 90 0
Python string strip 81 0
Python string rstrip 91 0
Python string lstrip 79 0
Python string rjust 96 0
Python string ljust 95 0
Python string len 82 0
Python string join 75 0
Python string casefold 82 0
Python string isprintable 85 0
Python string encode 78 0
Python string isdecimal 84 0
Python string isidentifier 78 0
Python string isupper 78 0
Python string istitle 80 0
Python string isspace 100 0
Python string isnumeric 102 0
Python string isdigit 82 0
Python string islower 84 0
Python string isalpha 96 0
Python string isalnum 102 0
Python string index 87 0
Python string find 93 0
Python string expandtabs() 81 0
Python string endswith 91 0
Python string count 86 0
Python string capitalize 78 0
Python string center 84 0
Python string Introduction 99 0
Python string Template 140 0
Python string Formatter 145 0
Python string printable 199 0
Python string whitespace 146 0
Python string punctuation 104 0
Python string octdigits 86 0
Python string hexdigits 104 0
Python string digits 80 0
Python string ascii_letters 344 0
Python string ascii_lowercase 147 0
Python string ascii_uppercase 156 0
How to Create Download Manager in Python 524 0
Python random weibullvariate 164 0
python random paretovariate 133 0
Python random vonmisesvariate 178 0
Python random normalvariate 196 0
Python random lognormvariate 120 0
Python random gauss 120 0
Python random gammavariate 131 0
Python random expovariate 194 0
Python random betavariate 186 0
Python random triangular 117 0
Python random uniform 141 0
Python random random 117 0
Python random sample 182 0
Python random shuffle 178 0
Python random choices 234 0
Python random choice 166 0
Python random randint 148 0
Python random randrange 214 0
Python random getrandbits 141 0
Python random setstate 136 0
Python random getstate 178 0
Python random seed 168 1
Python random Introduction 175 0

Comments