String Operators & Method
String Operators & Method
Operator Description
It is known as concatenation operator used to join the strings given
+
either side of the operator.
It is used to specify the raw string. Raw strings are used in the cases
where we need to print the actual meaning of escape characters such
r/R
as "C://python". To define any string as a raw string, the character r
or R is followed by the string.
print(str[2:4]); # ll
print('w' in str) # false (as w is not present in str)
print('wo' not in str1) # false (as wo is present in str1)
print(r'C://python37') # C://python37 as it is written
print("The string str : %s"%(str)) # The string str : Hello
String Methods:
Method Description
It capitalizes the first character of the String. This function is
capitalize() deprecated in python3.
casefold() Converts string into lower case.
It returns a space padded string with the original string centred
center(width , fillchar) with equal number of left and right spaces.
It counts the number of occurrences of a substring in a String
count(Substr, begin, end) between begin and end index.
It returns a Boolean value if the string terminates with given
endswith(suffix , beg, end) suffix between begin and end.
It returns a Boolean value if the string starts with given str
startswith(suffix, beg, end) between begin and end.
It defines tabs in string to multiple spaces. The default space
expandtabs(tabsize = 8) value is 8.
find(Substr , beg, end) It returns the index value of the string where substring (first
occurrence) is found between begin index and end index.
(returns -1 if the value is not found)
It is similar to find but it traverses the string in backward
rfind(Substr, beg, end) direction.
It throws an exception if string is not found. It works same as
index(Substr, beg, end) find() method.
It is same as index but it traverses the string in backward
rindex(Substr, beg, end) direction.
format(value) It returns a formatted version of S, using the passed value.
It returns true if the characters in the string are alphanumeric
isalnum() i.e., alphabets or numbers. Otherwise, it returns false. It does
not allow special chars even spaces.
It returns true if all the characters of the string are decimals (0-
isdecimal() 9).
It returns true if all the characters are digits (0-0), it also
isdigit() return True for some other unicode-supported chars.
isalpha() It returns true if all the characters are alphabets and there is at
least one character, otherwise False.
isidentifier() It returns true if the string is the valid identifier.
It returns true if the characters of a string are in lower case,
islower() otherwise false.
It returns true if characters of a string are in Upper case,
isupper() otherwise False.
isnumeric() It returns true if the string contains only numeric characters.
It returns true if all the characters of s are printable or s is
isprintable() empty, false otherwise.
It returns true if the characters of a string are only white-
isspace() spaces, otherwise false.
It returns true if the string is titled properly and false
otherwise. A title string is the one in which the first character of
istitle() every word is upper-case whereas the other characters are
lower-case.
join(seq) It merges the strings representation of the given sequence.
len(string) It returns the length of a string.
It returns the space padded strings with the original string left
ljust(width, fillchar) justified to the given width.
Returns a space padded string having original string right
rjust(width ,fillchar) justified to the number of characters specified.
lower() It converts all the characters of a string to Lower case.
upper() It converts all the characters of a string to Upper Case.
It removes all leading whitespaces of a string and can also be
lstrip(chars) used to remove particular character from leading.
It removes all trailing whitespace of a string and can also be
rstrip(chars) used to remove particular character from trailing.
strip(chars) It is used to perform lstrip() and rstrip() on the string.
It searches for the separator sep in S, and returns the part
partition() before it, the separator itself, and the part after it. If the
separator is not found, return S and two empty strings.
rpartition() Same as partition() but it splits the string at the last occurrence
of seperator substring.
casefold()
txt = "Hello, And Welcome To My World!"
x = txt.casefold() # hello, and welcome to my world!
center(length, character)
length (Required). The length of the returned string
character (Optional). The character to fill the missing space on each side. Default is space.
txt = "abcd"
x = txt.center(12, "O") # OOOOabcdOOOO
y = txt.center(11, "O") # OOOOabcdOOO
expandtabs(tabsize)
txt = "H\te\tl\tl\to"
x = txt.expandtabs() # H e l l o
x = txt.expandtabs(2) # H e l l o
find (value, start, end) and rfind (value, start, end)
value- Required. The value to search for
start- Optional. Where to start the search. Default is 0
end- Optional. Where to end the search. Default is end of the string
txt = "Hello, welcome to my world, welcome."
print(txt.find("welcome")) # 7
print(txt.rfind("welcome")) # 28
format(value1, value2...)
The format() method formats the specified value(s) and insert them inside the string's
placeholder. The placeholder is defined using curly brackets: {}. The values can be of any data
type.
The placeholders can be identified using named indexes {price}, numbered indexes {0}, or even
empty placeholders {}.
txt1 = "My name is {fname}, I'am {age}".format(fname = "John", age = 36)
txt2 = "My name is {0}, I'am {1}".format("John",36)
txt3 = "My name is {}, I'am {}".format("John",36)
print(txt1) # My name is John, I'm 36
print(txt2) # My name is John, I'm 36
print(txt3) # My name is John, I'm 36
isalnum()
print("Company 12".isalnum()) # False
print("Company12".isalnum()) # True
print("Company_12".isalnum()) # False
isdecimal()
print("30".isdecimal()) # True
print("010".isdecimal()) # True
print("47.5".isdecimal()) # False
print("40,000".isdecimal()) # False
isdigit()
print("30".isdigit()) # True
print("010".isdigit()) # True
print("47.5".isdigit()) # False
print("40,000".isdigit()) # False
Main difference between the function str.isdecimal() and str.isdigit() is that:
str.isdecimal() return True only for numbers from 0 to 9, at the same time the
str.isdigit() return True for some other unicode-supported chars.
a = "\u0030" #unicode for 0
b = "\u00B2" #unicode for ²
print(a.isdecimal()) # True
print(b.isdecimal()) # False
print(a.isdigit()) # True
print(b.isdigit()) # True
isalpha()
print("Company".isalpha()) # True
print("Company10".isalpha()) # False
isidentifier()
print("MyFolder".isidentifier()) # True
print("Demo002".isidentifier()) # True
print("2bring".isidentifier()) # False
print("my demo".isidentifier()) # False
isnumeric()
Numeric characters include digit and all the characters which have the
Unicode numeric value property. Like ² and ¾ are also considered to be
numeric values.
print("12345".isnumeric()) # True
print("123abc".isnumeric()) # False
print("123-4525-00".isnumeric()) # False
print("\u0030".isnumeric()) # True (unicode for 0)
print("\u00B2".isnumeric()) # True (unicode for ²)
print("10km2".isnumeric()) # False
isprintable()
print("Hello, Ptyhon" .isprintable()) # True
print("Learn Python here\n".isprintable()) # False
print("\t Python is a programming language".isprintable()) # False
isspace()
print(" ".isspace()) # True
print(" s ".isspace()) # False
istitle()
print("HELLO, AND WELCOME TO MY WORLD".istitle()) # False
print("Hello Abc".istitle()) # True
print("22 Names".istitle()) # True
print("This ABC".istitle()) # False
join(iterable)
Join all items in a tuple into a string, using a hash character as separator. It
allows various iterables like: List, Tuple, String etc.
str1="ABCD"
str2="x".join(str1)
print(str2) # AxBxCxD
len(string)
print(len("AB CD")) #5
ljust(width, fillchar) and rjust(width, fillchar)
ljust() method left justify the string and fill the remaining spaces with fillchars.
width: width of the given string.
fillchar: characters to fill the remaining space in the string. It is optional.
txt = "Python"
x = txt.ljust(20,'+')
y = txt.rjust(20,'+')
print(x) # Python++++++++++++++
print(y) # ++++++++++++++Python
txt = ",,,,,ssaaww.....python"
x = txt.lstrip(",.asw")
print(x) # python
txt = ",,,,,ssaaXww.....python"
x = txt.lstrip(",.asw")
print(x) # Xww.....python
txt = "python,,,,,ssqqqww....."
x = txt.rstrip(",.qsw")
print(x) # python
txt = ",,,,,rrttgg.....python....rrr"
x = txt.strip(",.grt")
print(x) # python
Example:
Search for the word "apple", and return a tuple with three elements:
1 - everything before the "match"
2 - the "match"
3 - everything after the "match"
y = txt.rpartition("xyz")
print(y) # ('abc xyz def ', 'xyz', ' ghi')
a = txt.partition("zzz")
print(a) # ('abc xyz def xyz ghi', '', '')
b = txt.rpartition("zzz")
print(b) # ('', '', 'abc xyz def xyz ghi')
swapcase()
print("Python Program".swapcase()) # pYTHON pROGRAM
title()
It returns a string where the first character in every word is upper case. If the word contains
a number or a symbol, the first letter after that will be converted to upper case.
translate(table)
It returns a string in which each character has been mapped through the given translation
table. We can use maketrans() method to create a translation map from character-to-
character mappings in different formats.
table = {97 : 103, 101 : None, 111 : 112}
str = "abcdefghijklmnopqrstuvwxyz"
str2 = str.translate(table)
print(str2) # gbcdfghijklmnppqrstuvwxyz
zfill(len)
It adds zeros (0) at the beginning of the string, until it reaches the specified length. It returns
original length string if the width is less than string length.
a = "hello"
b = "welcome to the jungle"
c = "10.000"
print(a.zfill(10)) # 00000hello
print(b.zfill(10)) # welcome to the jungle
print(c.zfill(10)) # 000010.000