Strings in Python
Strings in Python
in python
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.
Example:
var1 = 'Hello World!'
var2 = "Python Programming"
print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])
Output:
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.
Example:
var1 = 'Hello World!'
print ("Updated String :- ", var1[:6] + 'Python')
Output:
Updated String :- Hello Python
Slicing of Strings
To access a range of characters in the String, method of slicing is
used. Slicing in a String is done by using a Slicing operator (colon).
Example:
String1 = “SmileStudents"
print("Initial String: ")
print(String1)
print("\nSlicing characters from 3-12: ")
print(String1[3:12])
print("\nSlicing characters between " +"3rd and 2nd last character:
")
print(String1[3:-2])
Output:
Initial String:
SmileStudents
Syntax
str.capitalize()
Example
str = "this is string example....wow!!!"
print ("str.capitalize() : ", str.capitalize())
Output:
str.capitalize() : This is string example....wow!!!
count()
The count() method 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
sub − This is the substring to be searched.
start − Search starts from this index. First character starts from 0
index. By default search starts from 0 index.
end − Search ends from this index. First character starts from 0
index. By default search ends at the last index.
Example
Output:
str.count('i') : 3
str.count('exam', 10, 40) : 1
find()
The find() method determines if the string str occurs in string, or in
a substring of string if the starting index beg and ending index end
are given.
Syntax
str.find(str, beg = 0 end = len(string))
Parameters
str − This specifies the string to be searched.
beg − This is the starting index, by default its 0.
end − This is the ending index, by default its equal to the length of
the string.
Example
print (str1.find(str2))
print (str1.find(str2, 10))
print (str1.find(str2, 40))
Output:
15
15
-1
index()
The index() method determines if the string str occurs in string
or in a substring of string, if the 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
str − This specifies the string to be searched.
beg − This is the starting index, by default its 0.
end − This is the ending index, by default its equal to the length
of the string.
Example
Output:
15
15
Traceback (most recent call last):
File "test.py", line 7, in <module>
print (str1.index(str2, 40))
ValueError: substring not found shell returned 1
len()
The len() method returns the length of the string.
Syntax
len( str )
Example
str = "this is string example....wow!!!"
print ("Length of the string: ", len(str))
Output:
Length of the string: 32
join()
The join() method returns a string in which the string elements
of sequence have been joined by str separator.
Syntax
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
s = "-"
seq = ("a", "b", "c") # This is sequence of strings.
print (s.join( seq ))
Output:
a-b-c
lower()
The method lower() returns a copy of the string in which all
case-based characters have been lowercased.
Syntax
str.lower()
Example
str = "THIS IS STRING EXAMPLE....WOW!!!"
print (str.lower())
Output:
this is string example....wow!!!
upper()
The upper() method returns a copy of the string in which all
case-based characters have been uppercased.
Syntax
str.upper()
Example
str = "this is string example....wow!!!"
print ("str.upper : ",str.upper())
Output:
str.upper : THIS IS STRING EXAMPLE....WOW!!!
title()
The title() method returns a copy of the string in which first
characters of all the words are capitalized.
Syntax
str.title()
Example
str = "this is string example....wow!!!"
print (str.title())
Output:
This Is String Example....Wow!!!
max()
The max() method returns the max alphabetical character from the
string str.
Syntax
max(str)
Example
str = "this is a string example....really!!!"
print ("Max character: " + max(str))
str = "this is a string example....wow!!!"
print ("Max character: " + max(str))
Output:
Max character: y
Max character: x
min()
The min() method returns the min alphabetical character from the
string str.
Syntax
min(str)
Example
str = "www.google.com"
print ("Min character: " + min(str))
str = “ALPHABET"
print ("Min character: " + min(str))
Output:
Min character: .
Min character: A
replace()
The replace() method 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
str.replace(old, new[, max])
Parameters
old − This is old substring to be replaced.
new − This is new substring, which would replace old substring.
max − If this optional argument max is given, only the first count
occurrences are replaced.
Example
Output:
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
split()
The split() method 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
str.split(str="", num = string.count(str)).
Parameters
str − This is any delimeter, by default it is space.
num − this is number of lines to be made
Return Value
This method returns a list of lines.
Example
Output:
['this', 'is', 'string', 'example....wow!!!']
['th', 's is string example....wow!!!']
['this is string example....', 'o', '!!!']
swapcase()
The swapcase() method returns a copy of the string in which all the
case-based characters have had their case swapped.
Syntax
str.swapcase();
Example
str = "this is string example....wow!!!"
print (str.swapcase())
str = "This Is String Example....WOW!!!"
print (str.swapcase())
Output:
THIS IS STRING EXAMPLE....WOW!!!
tHIS iS sTRING eXAMPLE....wow!!!
center()
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
width − This is the total width of the string.
fillchar − This is the filler character.
Return Value
This method returns a string that is at least width characters wide,
created by padding the string with the character fillchar (default is a
space).
Example
Output:
str.center(40, 'a') : aaaathis is string example....wow!!!aaaa
startswith()
Syntax
str.startswith(str, beg = 0,end = len(string));
Parameters
str − This is the string to be checked.
beg − This is the optional parameter to set start index of the
matching boundary.
end − This is the optional parameter to set start index of the
matching boundary.
Return Value
This method returns true if found matching string otherwise false
Example
Output:
True
True
False
endswith()
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
suffix − This could be a string or could also be a tuple of
suffixes to look for.
start − The slice begins from here.
end − The slice ends here.
Example
suffix = 'exam'
print (Str.endswith(suffix))
print (Str.endswith(suffix, 0, 19))
Output:
True
True
False
True
ljust()
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
str.ljust(width[, fillchar])
Example
str = "this is string example....wow!!!"
print str.ljust(50, '*')
Output:
this is string example....wow!!!******************
rjust()
The rjust() 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).
Syntax
str.rjust(width[, fillchar])
Parameters
width − This is the string length in total after padding.
fillchar − This is the filler character, default is a space.
Example
str = "this is string example....wow!!!"
print (str.rjust(50, '*'))
Output:
******************this is string example....wow!!!
rfind()
The rfind() method 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
str.rfind(str, beg = 0 end = len(string))
Example
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))
Output:
5 5 -1 2 2 -1
rindex()
The rindex() method 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].
Example
str1 = "this is really a string example....wow!!!"
str2 = "is"
print (str1.rindex(str2))
print (str1.rindex(str2,10))
Output:
5 Traceback (most recent call last):
File "test.py", line 5, in <module>
print (str1.rindex(str2,10))
ValueError: substring not found
strip()
The strip() method 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
str.strip([chars]);
Parameters
chars − The characters to be removed from beginning or end of the
string.
Return Value
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
Output:
this is string example....wow!!!
lstrip()
Syntax: str.lstrip([chars])
Example:
str = " this is string example....wow!!!"
print (str.lstrip())
str = "*****this is string example....wow!!!*****"
print (str.lstrip('*'))
Output:
this is string example....wow!!!
this is string example....wow!!!*****
rstrip()
The rstrip() method returns a copy of the string in which all chars
have been stripped from the end of the string (default whitespace
characters).
Syntax: str.rstrip([chars])
Example
str = " this is string example....wow!!! "
print (str.rstrip())
str = "*****this is string example....wow!!!*****"
print (str.rstrip('*'))
Output:
this is string example....wow!!!
*****this is string example....wow!!!
isalnum()
The isalnum() method checks whether the string consists of
alphanumeric characters.
Syntax
str.isa1num()
Example
str = "this2016" # No space in this string
print (str.isalnum())
str = "this is string example....wow!!!"
print (str.isalnum())
Output:
True
False
isalpha()
The isalpha() method checks whether the string consists of
alphabetic characters only.
Syntax
str.isalpha()
Example
str = "this"; # No space & digit in this string
print (str.isalpha())
str = "this is string example....wow!!!"
print (str.isalpha())
Output:
True
False
isdigit()
Syntax
str.isdigit()
Example
str = "123456"; # Only digit in this string
print (str.isdigit())
str = "this is string example....wow!!!"
print (str.isdigit())
Output:
True
False
islower()
The islower() method checks whether all the case-based characters
(letters) of the string are lowercase.
Syntax
str.islower()
Example
str = "THIS is string example....wow!!!"
print (str.islower())
str = "this is string example....wow!!!"
print (str.islower())
Output:
False
True
isnumeric()
The isnumeric() method checks whether the string consists of only
numeric characters. This method is present only on unicode objects.
Syntax
str.isnumeric()
Example
str = "this2016"
print (str.isnumeric())
str = "23443434"
print (str.isnumeric())
Output:
False
True
isspace()
The isspace() method checks whether the string consists of
whitespace.
Syntax
str.isspace()
Example
str = " "
print (str.isspace())
str = "This is string example....wow!!!"
print (str.isspace())
Output:
True
False
istitle()
The istitle() method 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
str.istitle()
Example:
str = "This Is String Example...Wow!!!"
print (str.istitle())
str = "This is string example....wow!!!"
print (str.istitle())
Output:
True
False
isupper()
The isupper() method checks whether all the case-based characters
(letters) of the string are uppercase.
Syntax
str.isupper()
Example
str = "THIS IS STRING EXAMPLE....WOW!!!"
print (str.isupper())
str = "THIS is string example....wow!!!"
print (str.isupper())
Output:
True
False