Python Strings

Python Strings

June 14, 2018
19 minutes read time
1 likes
0 comments
444 times viewed


header image

Description

This article will guide you about the use of strings in python. It will explain various functionalities and builtin functions associated with it.

Content

String

String Methods & its Description

capitalize()

Capitalizes first letter of string

>>> str = "this is string example....wow!!!"
>>> print(str.capitalize())
This is string example....wow!!!

center(width, fillchar)

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

>>> str = "this is string example....wow!!!"
>>> print(str.center(40, 'a'))
aaaathis is string example....wow!!!aaaa

count(str, beg = 0,end = len(string))

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

>>> str = "this is string example....wow!!!"
>>> sub = 'i'
>>> str.count(sub)
3
>>> sub = 'exam'
>>> str.count(sub,10,40)
1

decode(encoding = ‘UTF-8’,errors = ‘strict’)

Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding

Str = "this is string example....wow!!!"
Str = Str.encode('base64','strict')

print "Encoded String: " + Str
print "Decoded String: " + Str.decode('base64','strict')

# Encoded String: b'dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE='
# Decoded String: this is string example....wow!!!

encode(encoding = ‘UTF-8’,errors = ‘strict’)

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

Str = "this is string example....wow!!!"
Str = base64.b64encode(Str.encode('utf-8',errors = 'strict'))
print ("Encoded String: " , Str)

# Encoded String: b'dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE='

endswith(suffix, beg = 0, end = len(string))

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

Str='this is string example....wow!!!'
suffix='!!'
print (Str.endswith(suffix))
print (Str.endswith(suffix,20))
suffix='exam'
print (Str.endswith(suffix))
print (Str.endswith(suffix, 0, 19))

# True
# True
# False
# True

eval(str)

Evaluates a string and returns an object.

expandtabs(tabsize = 8)

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

str = "this is\tstring example....wow!!!"

print ("Original string: " + str)
print ("Defualt exapanded tab: " +  str.expandtabs())
print ("Double exapanded tab: " +  str.expandtabs(16))

# Original string: this is        string example....wow!!!
# Defualt exapanded tab: this is string example....wow!!!
# Double exapanded tab: this is         string example....wow!!!

find(str, beg = 0 end = len(string))

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

str1 = "this is string example....wow!!!"
str2 = "exam";

print (str1.find(str2))
print (str1.find(str2, 10))
print (str1.find(str2, 40))

# 15
# 15
# -1

index(str, beg = 0, end = len(string))

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

str1 = "this is string example....wow!!!"
str2 = "exam";

print (str1.index(str2))
print (str1.index(str2, 10))
print (str1.index(str2, 40))

# 15
# 15
# Traceback (most recent call last):
#    File "test.py", line 7, in 
#       print (str1.index(str2, 40))
# ValueError: substring not found
# shell returned 1

int(x [,base])

Converts x to an integer. Base specifies the base if x is a string.

print(int('1945'))
print(int('100',2))
print(int('13', 8)
print(int('a5', 16)

# 1945
# 4
# 11
# 165

isalnum()

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

str = "this2016"  # No space in this string
print (str.isalnum())

str = "this is string example....wow!!!"
print (str.isalnum())

# True
# False

isalpha()

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

str = "this";  # No space & digit in this string
print (str.isalpha())

str = "this is string example....wow!!!"
print (str.isalpha())

# True
# False

isdecimal()

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

str = "this2016"
print (str.isdecimal())

str = "23443434"
print (str.isdecimal())

# False
# True

isdigit()

Returns true if string contains only digits and false otherwise.

str = "123456";  # Only digit in this string
print (str.isdigit())

str = "this is string example....wow!!!"
print (str.isdigit())

# True
# False

islower()

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

str = "THIS is string example....wow!!!"
print (str.islower())

str = "this is string example....wow!!!"
print (str.islower())

# False
# True

isnumeric()

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

str = "this2016"  
print (str.isnumeric())

str = "23443434"
print (str.isnumeric())

# False
# True

isspace()

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

str = "       " 
print (str.isspace())

str = "This is string example....wow!!!"
print (str.isspace())

# True
# False

istitle()

Returns true if string is properly “titlecased” and false otherwise.

str = "This Is String Example...Wow!!!"
print (str.istitle())

str = "This is string example....wow!!!"
print (str.istitle())

# True
# False

isupper()

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

str = "THIS IS STRING EXAMPLE....WOW!!!"
print (str.isupper())

str = "THIS is string example....wow!!!"
print (str.isupper())

# True
# False

join(seq)

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

s = "-"
seq = ("a", "b", "c") # This is sequence of strings.
print (s.join( seq ))

# a-b-c

len(string)

Returns the length of the string

str = "this is string example....wow!!!"
print ("Length of the string: ", len(str))

# Length of the string:  32

ljust(width[, fillchar])

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

str = "this is string example....wow!!!"
print str.ljust(50, '*')

# this is string example....wow!!!******************

lower()

Converts all uppercase letters in string to lowercase.

str = "THIS IS STRING EXAMPLE....WOW!!!"
print (str.lower())

# this is string example....wow!!!

lstrip()

Removes all leading whitespace in string.

str = "     this is string example....wow!!!"
print (str.lstrip())

str = "*****this is string example....wow!!!*****"
print (str.lstrip('*'))

# this is string example....wow!!!
# this is string example....wow!!!*****

maketrans()

Returns a translation table to be used in translate function

from string import maketrans # Required to call maketrans function.

intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)

str = "this is string example....wow!!!"
print (str.translate(trantab))

# th3s 3s str3ng 2x1mpl2....w4w!!!

max(str)

Returns the max alphabetical character from the string str.

str = "this is a string example....really!!!"
print ("Max character: " + max(str))

str = "this is a string example....wow!!!"
print ("Max character: " + max(str))

# Max character: y
# Max character: x

min(str)

Returns the min alphabetical character from the string str.

str = "www.tutorialspoint.com"
print ("Min character: " + min(str))

str = "TUTORIALSPOINT"
print ("Min character: " + min(str))

# Min character: .
# Min character: A

ord(x)

Converts a single character to its integer value.

print(ord('A'))
print(ord('z'))

# 65
# 122

replace(old, new [, max])

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

str = "this is string example....wow!!! this is really string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))

# thwas was string example....wow!!! thwas was really string
# thwas was string example....wow!!! thwas is really string

repr(x)

Converts object x to an expression string.

print(str("as34dft6y"))

# "'as34dft6y'"

rfind(str, beg = 0,end = len(string))

Same as find(), but search backwards in string

str1 = "this is really a string example....wow!!!"
str2 = "is"

print (str1.rfind(str2))

print (str1.rfind(str2, 0, 10))
print (str1.rfind(str2, 10, 0))

print (str1.find(str2))
print (str1.find(str2, 0, 10))
print (str1.find(str2, 10, 0))

# 5
# 5
# -1
# 2
# 2
# -1

rindex( str, beg = 0, end = len(string))

Same as index(), but search backwards in string

str1 = "this is really a string example....wow!!!"
str2 = "is"

print (str1.rindex(str2))
print (str1.rindex(str2,10))

# 5
# Traceback (most recent call last):
#    File "test.py", line 5, in <module>
#       print (str1.rindex(str2,10))
# ValueError: substring not found

rjust(width,[, fillchar])

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

str = "this is string example....wow!!!"
print (str.rjust(50, '*'))

# ******************this is string example....wow!!!

rstrip()

Removes all trailing whitespace of string

str = "     this is string example....wow!!!     "
print (str.rstrip())

str = "*****this is string example....wow!!!*****"
print (str.rstrip('*'))

#      this is string example....wow!!!
# *****this is string example....wow!!!

split(str=”“, num=string.count(str))

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

str = "this is string example....wow!!!"
print (str.split( ))
print (str.split('i',1))
print (str.split('w'))

# ['this', 'is', 'string', 'example....wow!!!']
# ['th', 's is string example....wow!!!']
# ['this is string example....', 'o', '!!!']

splitlines( num=string.count(‘\n’))

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

str = "this is \nstring example....\nwow!!!"
print (str.splitlines( ))

# ['this is ', 'string example....', 'wow!!!']

startswith(str, beg=0,end=len(string))

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

str = "this is string example....wow!!!"
print (str.startswith( 'this' ))
print (str.startswith( 'string', 8 ))
print (str.startswith( 'this', 2, 4 ))

# True
# True
# False

str(x)

Converts object x to a string representation.

print(str("as34dft6y"))

# 'as34dft6y'

strip([chars])

Performs both lstrip() and rstrip() on string

str = "*****this is string example....wow!!!*****"
print (str.strip( '*' ))

# this is string example....wow!!!

swapcase()

Inverts case for all letters in string

str = "this is string example....wow!!!"
print (str.swapcase())

str = "This Is String Example....WOW!!!"
print (str.swapcase())

# THIS IS STRING EXAMPLE....WOW!!!
# tHIS iS sTRING eXAMPLE....wow!!!

title()

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

str = "this is string example....wow!!!"
print (str.title())

# This Is String Example....Wow!!!

translate(table, deletechars=”“)

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

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))

# th3s 3s str3ng 2x1mpl2....w4w!!!

Following is the example to delete ‘x’ and ‘m’ characters from the string

from string import maketrans   # Required to call maketrans function.

intab = "aeiou"
outtab = "12345"
deltab = "xm" #added line
trantab = str.maketrans(intab, outtab, deltab)

str = "this is string example....wow!!!"
print (str.translate(trantab))

# th3s 3s str3ng 21pl2....w4w!!!

upper()

Converts lowercase letters in string to uppercase.

str = "this is string example....wow!!!"
print ("str.upper : ",str.upper())

# str.upper :  THIS IS STRING EXAMPLE....WOW!!!

zfill(width)

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

str = "this is string example....wow!!!"
print ("str.zfill : ",str.zfill(40))
print ("str.zfill : ",str.zfill(50))

# str.zfill :  00000000this is string example....wow!!!
# str.zfill :  000000000000000000this is string example....wow!!!


We are done



Like this post

1   Like


Share this post on

Google Plus LinkedIn


About the author




Join the discussion

Nothing to preview

Post Comment



Comments