PYTHON - STRINGSStrings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. For example:
var1 = 'Hello World!'
var2 = "Python Programming" Accessing Values in Strings Python does not support a character type; these are treated as strings of length one, thus also considered a substring. To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. For example:
#!/usr/bin/python
var1 = 'Hello World!' var2 = "Python Programming" print "var1[0]: ", var1[0] print "var2[1:5]: ", var2[1:5] When the above code is executed, it produces the following result:
var1[0]: H
var2[1:5]: ytho
Updating Strings You can "update" an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether. For example:
#!/usr/bin/python
var1 = 'Hello World!' print "Updated String :- ", var1[:6] + 'Python' When the above code is executed, it produces the following result:
Updated String :- Hello Python
Escape Characters Following table is a list of escape or non-printable characters that can be represented with backslash notation. An escape character gets interpreted; in a single quoted as well as double quoted strings.
Assume string variable a holds 'Hello' and variable b holds 'Python', then:
One of Python's coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C's printf() family. Following is a simple example:
#!/usr/bin/python
print "My name is %s and weight is %d kg!" % ('Zara', 21) When the above code is executed, it produces the following result:
My name is Zara and weight is 21 kg!
Here is the list of complete set of symbols which can be used along with %:
Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters. The syntax for triple quotes consists of three consecutive single or double quotes.
#!/usr/bin/python
para_str = """this is a long string that is made up of several lines and non-printable characters such as TAB ( \t ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ \n ], or just a NEWLINE within the variable assignment will also show up. """ print para_str; When the above code is executed, it produces the following result. Note how every single special character has been converted to its printed form, right down to the last NEWLINE at the end of the string between the "up." and closing triple quotes. Also note that NEWLINEs occur either with an explicit carriage return at the end of a line or its escape code (\n):
this is a long string that is made up of
several lines and non-printable characters such as TAB ( ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ ], or just a NEWLINE within the variable assignment will also show up. Raw strings do not treat the backslash as a special character at all. Every character you put into a raw string stays the way you wrote it:
#!/usr/bin/python
print 'C:\\nowhere' When the above code is executed, it produces the following result:
C:\nowhere
Now let's make use of raw string. We would put expression in r'expression' as follows:
#!/usr/bin/python
print r'C:\\nowhere' When the above code is executed, it produces the following result:
C:\\nowhere
Unicode StringUnicode StringUnicode StringUnicode StringUnicode StringUnicode StringUnicode StringUnicode StringUnicode StringUnicode StringUnicode StringUnicode StringUnicode StringUnicode String Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16-bit Unicode. This allows for a more varied set of characters, including special characters from most languages in the world. I'll restrict my treatment of Unicode strings to the following:
#!/usr/bin/python
print u'Hello, world!' When the above code is executed, it produces the following result:
Hello, world!
As you can see, Unicode strings use the prefix u, just as raw strings use the prefix r. Built-in String Methods Python includes the following built-in methods to manipulate strings:
1. capitalize() Method It returns a copy of the string with only its first character capitalized. Syntax
str.capitalize()
Parameters NA Return Value string Example
#!/usr/bin/python
str = "this is string example....wow!!!"; print "str.capitalize() : ", str.capitalize() Result
str.capitalize() : This is string example....wow!!!
2. center(width, fillchar) Method The method center() returns centered in a string of length width. Padding is done using the specified fillchar. Default filler is a space. Syntax
str.center(width[, fillchar])
Parameters
This method returns centered in a string of length width. Example
#!/usr/bin/python
str = "this is string example....wow!!!"; print "str.center(40, 'a') : ", str.center(40, 'a') Result
str.center(40, 'a') : aaaathis is string example....wow!!!aaaa
3. count(str, beg= 0,end=len(string)) Method The method count() returns the number of occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Syntax
str.count(sub, start= 0,end=len(string))
Parameters
Centered in a string of length width. Example
#!/usr/bin/python
str = "this is string example....wow!!!"; sub = "i"; print "str.count(sub, 4, 40) : ", str.count(sub, 4, 40) sub = "wow"; print "str.count(sub) : ", str.count(sub) Result
str.count(sub, 4, 40) : 2
str.count(sub, 4, 40) : 1 4. decode(encoding='UTF-8',errors='strict') Method The method decode() decodes the string using the codec registered for encoding. It defaults to the default string encoding. Syntax
str.decode(encoding='UTF-8',errors='strict')
Parameters
Decoded string. Example
#!/usr/bin/python
str = "this is string example....wow!!!"; str = str.encode('base64','strict'); print "Encoded String: " + str; print "Decoded String: " + str.decode('base64','strict') Result
Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=
Decoded String: this is string example....wow!!!
5. encode(encoding='UTF-8',errors='strict') Method The method encode() returns an encoded version of the string. Default encoding is the current default string encoding. The errors may be given to set a different error handling scheme. Syntax
str.encode(encoding='UTF-8',errors='strict')
Parameters
Encoded string. Example
#!/usr/bin/python
str = "this is string example....wow!!!"; print "Encoded String: " + str.encode('base64','strict') Result
Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=
6. endswith(suffix, beg=0, end=len(string)) Method It returns True if the string ends with the specified suffix, otherwise return False optionally restricting the matching with the given indices start and end. Syntax
str.endswith(suffix[, start[, end]])
Parameters
TRUE if the string ends with the specified suffix, otherwise FALSE. Example
#!/usr/bin/python
str = "this is string example....wow!!!"; suffix = "wow!!!"; print str.endswith(suffix); print str.endswith(suffix,20); suffix = "is"; print str.endswith(suffix, 2, 4); print str.endswith(suffix, 2, 6); Result
True
True True False 7. expandtabs(tabsize=8) It returns a copy of the string in which tab characters ie. '\t' are expanded using spaces, optionally using the given tabsize (default 8). Syntax
str.expandtabs(tabsize=8)
Parameters
#!/usr/bin/python
str = "this is\tstring example....wow!!!"; print "Original string: " + str; print "Defualt exapanded tab: " + str.expandtabs(); print "Double exapanded tab: " + str.expandtabs(16); Result
Original string: this is string example....wow!!!
Defualt exapanded tab: this is string example....wow!!! Double exapanded tab: this is string example....wow!!! 8. find(str, beg=0 end=len(string)) It determines if string str occurs in string, or in a substring of string if starting index beg and ending index end are given. Syntax
str.find(str, beg=0 end=len(string))
Parameters
Index if found and -1 otherwise. Example
The following example shows the usage of find() method.
#!/usr/bin/python str1 = "this is string example....wow!!!"; str2 = "exam"; print str1.find(str2); print str1.find(str2, 10); print str1.find(str2, 40); Result
15
15 -1 9. index(str, beg=0, end=len(string)) It determines if string str occurs in string or in a substring of string if starting index beg and ending index end are given. This method is same as find(), but raises an exception if sub is not found. Syntax
str.index(str, beg=0 end=len(string))
Parameters
Index if found otherwise raises an exception if str is not found. Example
#!/usr/bin/python
str1 = "this is string example....wow!!!"; str2 = "exam"; print str1.index(str2); print str1.index(str2, 10); print str1.index(str2, 40); Result
15
15 Traceback (most recent call last): File "test.py", line 8, in print str1.index(str2, 40); ValueError: substring not found shell returned 1 10. isalnum() Method It checks whether the string consists of alphanumeric characters. Syntax
str.isa1num()
Parameters NA Return Value TRUE if all characters in the string are alphanumeric and there is at least one character, FASLE otherwise. Example
#!/usr/bin/python
str = "this2009"; # No space in this string print str.isalnum(); str = "this is string example....wow!!!"; print str.isalnum(); Result
True
False 11. isalpha() Description The method isalpha() checks whether the string consists of alphabetic characters only. Syntax Following is the syntax for islpha() method:
str.isalpha()
Parameters
This method returns true if all characters in the string are alphabetic and there is at least one character, false otherwise. Example The following example shows the usage of isalpha() method.
#!/usr/bin/python
str = "this"; # No space & digit in this string print str.isalpha(); str = "this is string example....wow!!!"; print str.isalpha(); When we run above program, it produces following result:
True
False 12. isdigit() Description The method isdigit() checks whether the string consists of digits only. Syntax Following is the syntax for isdigit() method:
str.isdigit()
Parameters
This method returns true if all characters in the string are digits and there is at least one character, false otherwise. Example The following example shows the usage of isdigit() method.
#!/usr/bin/python
str = "123456"; # Only digit in this string print str.isdigit(); str = "this is string example....wow!!!"; print str.isdigit(); When we run above program, it produces following result:
True
False 13. islower() Description The method islower() checks whether all the case-based characters (letters) of the string are lowercase. Syntax Following is the syntax for islower() method:
str.islower()
Parameters
This method returns true if all cased characters in the string are lowercase and there is at least one cased character, false otherwise. Example The following example shows the usage of islower() method.
#!/usr/bin/python
str = "THIS is string example....wow!!!"; print str.islower(); str = "this is string example....wow!!!"; print str.islower(); When we run above program, it produces following result:
False
True 14. isnumeric() Description The method isnumeric() checks whether the string consists of only numeric characters. This method is present only on unicode objects. Note: To define a string as Unicode, one simply prefixes a 'u' to the opening quotation mark of the assignment. Below is the example. Syntax Following is the syntax for isnumeric() method:
str.isnumeric()
Parameters
This method returns true if all characters in the string are numeric, false otherwise. Example The following example shows the usage of isnumeric() method.
#!/usr/bin/python
str = u"this2009"; print str.isnumeric(); str = u"23443434"; print str.isnumeric(); When we run above program, it produces following result:
False
True 15. isspace() Method Description The method isspace() checks whether the string consists of whitespace. Syntax Following is the syntax for isspace() method:
str.isspace()
Parameters
This method returns true if there are only whitespace characters in the string and there is at least one character, false otherwise. Example The following example shows the usage of isspace() method.
#!/usr/bin/python
str = " "; print str.isspace(); str = "This is string example....wow!!!"; print str.isspace(); When we run above program, it produces following result:
True
False 16. istitle() Description The method istitle() checks whether all the case-based characters in the string following non-casebased letters are uppercase and all other case-based characters are lowercase. Syntax Following is the syntax for istitle() method:
str.istitle()
Parameters
This method returns 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.It returns false otherwise. Example The following example shows the usage of istitle() method.
#!/usr/bin/python
str = "This Is String Example...Wow!!!"; print str.istitle(); str = "This is string example....wow!!!"; print str.istitle(); When we run above program, it produces following result:
True
False 17. isupper() Description The method isupper() checks whether all the case-based characters (letters) of the string are uppercase. Syntax Following is the syntax for isupper() method:
str.isupper()
Parameters NA Return Value This method returns true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise. Example The following example shows the usage of isupper() method.
#!/usr/bin/python
str = "THIS IS STRING EXAMPLE....WOW!!!"; print str.isupper(); str = "THIS is string example....wow!!!"; print str.isupper(); When we run above program, it produces following result:
True
False 18. join(seq) Description The method join() returns a string in which the string elements of sequence have been joined by str separator. Syntax Following is the syntax for join() method:
str.join(sequence)
Parameters sequence -- This is a sequence of the elements to be joined. Return Value This method returns a string, which is the concatenation of the strings in the sequence seq. The separator between elements is the string providing this method. Example The following example shows the usage of join() method.
#!/usr/bin/python
str = "-"; seq = ("a", "b", "c"); # This is sequence of strings. print str.join( seq ); When we run above program, it produces following result:
a-b-c
19. len(string) Description The method len() returns the length of the string. Syntax Following is the syntax for len() method:
len( str )
Parameters NA Return Value This method returns the length of the string. Example The following example shows the usage of len() method.
#!/usr/bin/python
str = "this is string example....wow!!!"; print "Length of the string: ", len(str); When we run above program, it produces following result:
Length of the string: 32
20. ljust(width[, fillchar]) Description The method ljust() returns 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). Syntax Following is the syntax for ljust() method:
str.ljust(width[, fillchar])
Parameters
This method returns 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). Example The following example shows the usage of ljust() method.
#!/usr/bin/python
str = "this is string example....wow!!!"; print str.ljust(50, '0'); When we run above program, it produces following result:
this is string example....wow!!!000000000000000000
21. lower() Description The method lower() returns a copy of the string in which all case-based characters have been lowercased. Syntax Following is the syntax for lower() method:
str.lower()
Parameters NA Return Value This method returns a copy of the string in which all case-based characters have been lowercased. Example The following example shows the usage of lower() method.
#!/usr/bin/python
str = "THIS IS STRING EXAMPLE....WOW!!!"; print str.lower(); When we run above program, it produces following result:
this is string example....wow!!!
22. lstrip() Description The method lstrip() returns a copy of the string in which all chars have been stripped from the beginning of the string (default whitespace characters). Syntax Following is the syntax for lstrip() method:
str.lstrip([chars])
Parameters chars -- You can supply what chars have to be trimmed. Return Value This method returns a copy of the string in which all chars have been stripped from the beginning of the string (default whitespace characters). Example The following example shows the usage of lstrip() method.
#!/usr/bin/python
str = " this is string example....wow!!! "; print str.lstrip(); str = "88888888this is string example....wow!!!8888888"; print str.lstrip('8'); When we run above program, it produces following result:
this is string example....wow!!!
this is string example....wow!!!8888888 23. maketrans() Description The method maketrans() returns a translation table that maps each character in the intabstring into the character at the same position in the outtab string. Then this table is passed to the translate() function. Note: Both intab and outtab must have the same length. Syntax Following is the syntax for maketrans() method:
str.maketrans(intab, outtab]);
Parameters
This method returns a translate table to be used translate() function. Example The following example shows the usage of maketrans() method. Under this, every vowel in a string is replaced by its vowel position:
#!/usr/bin/python
from string import maketrans # Required to call maketrans function. intab = "aeiou" outtab = "12345" trantab = maketrans(intab, outtab) str = "this is string example....wow!!!"; print str.translate(trantab); When we run above program, it produces following result:
th3s 3s str3ng 2x1mpl2....w4w!!!
24. max(str) Description The method max() returns the max alphabetical character from the string str. Syntax Following is the syntax for max() method:
max(str)
Parameters
This method returns the max alphabetical character from the string str. Example The following example shows the usage of max() method.
#!/usr/bin/python
str = "this is really a string example....wow!!!"; print "Max character: " + max(str); str = "this is a string example....wow!!!"; print "Max character: " + max(str); When we run above program, it produces following result:
Max character: y
Max character: x 25. min(str) Description The method min() returns the min alphabetical character from the string str. Syntax Following is the syntax for min() method:
min(str)
Parameters
This method returns the max alphabetical character from the string str. Example The following example shows the usage of min() method.
#!/usr/bin/python
str = "this-is-real-string-example....wow!!!"; print "Min character: " + min(str); str = "this-is-a-string-example....wow!!!"; print "Min character: " + min(str); When we run above program, it produces following result:
Min character: !
Min character: ! 26. replace(old, new [, max]) Description The method replace() returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max. Syntax Following is the syntax for replace() method:
str.replace(old, new[, max])
Parameters
This method returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument max is given, only the first count occurrences are replaced. Example The following example shows the usage of replace() method.
#!/usr/bin/python
str = "this is string example....wow!!! this is really string"; print str.replace("is", "was"); print str.replace("is", "was", 3); When we run above program, it produces following result:
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string 27. rfind(str, beg=0,end=len(string)) Description The method rfind() returns the last index where the substring str is found, or -1 if no such index exists, optionally restricting the search to string[beg:end]. Syntax Following is the syntax for rfind() method:
str.rfind(str, beg=0 end=len(string))
Parameters
This method returns last index if found and -1 otherwise. Example The following example shows the usage of rfind() method.
#!/usr/bin/python
str = "this is really a string example....wow!!!"; str = "is"; print str.rfind(str); print str.rfind(str, 0, 10); print str.rfind(str, 10, 0); print str.find(str); print str.find(str, 0, 10); print str.find(str, 10, 0); When we run above program, it produces following result:
5
5 -1 2 2 -1 28. rindex(str, beg=0, end=len(string)) Description The method rindex() returns the last index where the substring str is found, or raises an exception if no such index exists, optionally restricting the search to string[beg:end]. Syntax Following is the syntax for rindex() method:
str.rindex(str, beg=0 end=len(string))
Parameters
This method returns last index if found otherwise raises an exception if str is not found. Example The following example shows the usage of rindex() method.
#!/usr/bin/python
str1 = "this is string example....wow!!!"; str2 = "is"; print str1.rindex(str2); print str1.index(str2); When we run above program, it produces following result:
5
2 29. rjust(width,[, fillchar]) Description The method rjust() returns 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). Syntax Following is the syntax for rjust() method:
str.rjust(width[, fillchar])
Parameters
This method returns 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). Example The following example shows the usage of rjust() method.
#!/usr/bin/python
str = "this is string example....wow!!!"; print str.rjust(50, '0'); When we run above program, it produces following result:
000000000000000000this is string example....wow!!!
30. rstrip() Description The method rstrip() returns a copy of the string in which all chars have been stripped from the end of the string (default whitespace characters). Syntax Following is the syntax for rstrip() method:
str.rstrip([chars])
Parameters chars -- You can supply what chars have to be trimmed. Return Value This method returns a copy of the string in which all chars have been stripped from the end of the string (default whitespace characters). Example The following example shows the usage of rstrip() method.
#!/usr/bin/python
str = " this is string example....wow!!! "; print str.rstrip(); str = "88888888this is string example....wow!!!8888888"; print str.rstrip('8'); When we run above program, it produces following result:
this is string example....wow!!!
88888888this is string example....wow!!! 31. split(str="", num=string.count(str)) Description The method split() returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num. Syntax Following is the syntax for split() method:
str.split(str="", num=string.count(str)).
Parameters
This method returns a list of lines. Example The following example shows the usage of split() method.
#!/usr/bin/python
str = "Line1-abcdef \nLine2-abc \nLine4-abcd"; print str.split( ); print str.split(' ', 1 ); When we run above program, it produces following result:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd'] 32. splitlines(num=string.count('\n')) Description The method splitlines() returns a list with all the lines in string, optionally including the line breaks (if num is supplied and is true) Syntax Following is the syntax for splitlines() method:
str.splitlines( num=string.count('\n'))
Parameters
This method returns true if found matching string otherwise false. Example The following example shows the usage of splitlines() method.
#!/usr/bin/python
str = "Line1-a b c d e f\nLine2- a b c\n\nLine4- a b c d"; print str.splitlines( ); print str.splitlines( 0 ); print str.splitlines( 3 ); print str.splitlines( 4 ); print str.splitlines( 5 ); When we run above program, it produces following result:
['Line1-a b c d e f', 'Line2- a b c', '', 'Line4- a b c d']
['Line1-a b c d e f', 'Line2- a b c', '', 'Line4- a b c d'] ['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d'] ['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d'] ['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d'] 33. startswith(str, beg=0,end=len(string)) Description The method startswith() checks whether string starts with str, optionally restricting the matching with the given indices start and end. Syntax Following is the syntax for startswith() method:
str.startswith(str, beg=0,end=len(string));
Parameters
This method returns true if found matching string otherwise false. Example The following example shows the usage of startswith() method.
#!/usr/bin/python
str = "this is string example....wow!!!"; print str.startswith( 'this' ); print str.startswith( 'is', 2, 4 ); print str.startswith( 'this', 2, 4 ); When we run above program, it produces following result:
True
True False 34. strip([chars]) Description The method strip() returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (default whitespace characters). Syntax Following is the syntax for strip() method:
str.strip([chars]);
Parameters
This method returns a copy of the string in which all chars have been stripped from the beginning and the end of the string. Example The following example shows the usage of strip() method.
#!/usr/bin/python
str = "0000000this is string example....wow!!!0000000"; print str.strip( '0' ); When we run above program, it produces following result:
this is string example....wow!!!
35. swapcase Description The method swapcase() returns a copy of the string in which all the case-based characters have had their case swapped. Syntax Following is the syntax for swapcase() method:
str.swapcase();
Parameters NA Return Value This method returns a copy of the string in which all the case-based characters have had their case swapped. Example The following example shows the usage of swapcase() method.
#!/usr/bin/python
str = "this is string example....wow!!!"; print str.swapcase(); str = "THIS IS STRING EXAMPLE....WOW!!!"; print str.swapcase(); When we run above program, it produces following result: 36. title() Description The method title() returns a copy of the string in which first characters of all the words are capitalized. Syntax Following is the syntax for title() method:
str.title();
Parameters NA Return Value This method returns a copy of the string in which first characters of all the words are capitalized. Example The following example shows the usage of title() method.
#!/usr/bin/python
str = "this is string example....wow!!!"; print str.title(); When we run above program, it produces following result:
This Is String Example....Wow!!!
37. translate(table, deletechars="") Description The method translate() returns a copy of the string in which all characters have been translated using table (constructed with the maketrans() function in the string module), optionally deleting all characters found in the string deletechars. Syntax Following is the syntax for translate() method:
str.translate(table[, deletechars]);
Parameters
This method returns a translated copy of the string. Example The following example shows the usage of translate() method. Under this every vowel in a string is replaced by its vowel position:
#!/usr/bin/python
from string import maketrans # Required to call maketrans function. intab = "aeiou" outtab = "12345" trantab = maketrans(intab, outtab) str = "this is string example....wow!!!"; print str.translate(trantab); When we run above program, it produces following result:
th3s 3s str3ng 2x1mpl2....w4w!!!
Following is the example to delete 'x' and 'm' characters from the string:
#!/usr/bin/python
from string import maketrans # Required to call maketrans function. intab = "aeiou" outtab = "12345" trantab = maketrans(intab, outtab) str = "this is string example....wow!!!"; print str.translate(trantab, 'xm'); This will produce following result:
th3s 3s str3ng 21pl2....w4w!!!
38. upper() Description The method upper() returns a copy of the string in which all case-based characters have been uppercased. Syntax Following is the syntax for upper() method:
str.upper()
Parameters NA Return Value This method returns a copy of the string in which all case-based characters have been uppercased. Example The following example shows the usage of upper() method.
#!/usr/bin/python
str = "this is string example....wow!!!"; print "str.capitalize() : ", str.upper() When we run above program, it produces following result:
THIS IS STRING EXAMPLE....WOW!!!
39. zfill (width) Description The method zfill() pads string on the left with zeros to fill width. Syntax Following is the syntax for zfill() method:
str.zfill(width)
Parameters width -- This is final width of the string. This is the width which we would get after filling zeros. Return Value This method returns padded string. Example The following example shows the usage of zfill() method.
#!/usr/bin/python
str = "this is string example....wow!!!"; print str.zfill(40); print str.zfill(50); When we run above program, it produces following result:
00000000this is string example....wow!!!
000000000000000000this is string example....wow!!! 40. isdecimal() Description The method isdecimal() checks whether the string consists of only decimal characters. This method are present only on unicode objects. Note: To define a string as Unicode, one simply prefixes a 'u' to the opening quotation mark of the assignment. Below is the example. Syntax Following is the syntax for isdecimal() method:
str.isdecimal()
Parameters
This method returns true if all characters in the string are decimal, false otherwise. Example The following example shows the usage of isdecimal() method.
#!/usr/bin/python
str = u"this2009"; print str.isdecimal(); str = u"23443434"; print str.isdecimal(); When we run above program, it produces following result:
False
True |