Python Programming For Polytechnic-4
Python Programming For Polytechnic-4
Strings
Creating and Storing Strings
Strings are another basic data type available in Python. They consist of one or more characters
surrounded by matching quotation marks. For example,
>>> single_quote = 'This is a single message'
>>> double_quote = "Hey it is my book"
>>> single_char_string = "A"
>>> empty_string = ""
>>> empty_string = ''
>>> single_within_double_quote = "Opportunities don't happen. You create them."
>>> double_within_single_quote = "Why did she call the man 'smart'?"
>>> same_quotes = 'I\'ve an idea'
>>> triple_quote_string = '''This
is
triple
quote'‘’
>>> triple_quote_string
'This\nis\ntriple\nquote'
>>> type(single_quote)
<class 'str'>
The str() Function
The str() function returns a string which is considered an informal or nicely printable representation
of the given object. The syntax for str() function is,
str(object)
It returns a string version of the object. If the object is not provided, then it returns an empty string.
>>> str(10)
'10'
>>> create_string = str()
>>> type(create_string)
<class 'str'>
Basic String Operations
In Python, strings can also be concatenated using + sign and * operator is used to create a repeated sequence of
strings.
>>> string_1 = "face"
>>> string_2 = "book"
>>> concatenated_string = string_1 + string_2
>>> concatenated_string
'facebook'
>>> concatenated_string_with_space = "Hi " + "There"
>>> concatenated_string_with_space
'Hi There'
>>> singer = 50 + "cent"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> singer = str(50) + "cent"
>>> singer
'50cent'
>>> repetition_of_string = "wow" * 5
>>> repetition_of_string
'wowwowwowwowwow'
You can check for the presence of a string in another string using in and not in member-
ship operators. It returns either a Boolean True or False. The in operator evaluates to True
if the string value in the left operand appears in the sequence of characters of string value
in right operand. The not in operator evaluates to True if the string value in the left
operand does not appear in the sequence of characters of string value in right operand.
len(): The len() function calculates the number of characters in a string. The white space
characters are also counted.
max(): The max() function returns a character having highest ASCII value.
min(): The min() function returns character having lowest ASCII value.
For example,
>>> count_characters = len("eskimos")
>>> count_characters
7
>>> max("axel")
'x‘
>>> min("brad")
'a'
Accessing Characters in String by Index Number
Each character in the string occupies a position in the string. Each of the string’s
character corresponds to an index number. The first character is at index 0; the next character
is at index 1, and so on. The length of a string is the number of characters in it. You can access
each character in a string using a subscript operator i.e., a square bracket. Square brackets are
used to perform indexing in a string to get the value at a specific index or position. This is also
called subscript operator.
The index breakdown for the string "be yourself" assigned to word_phrase string variable is
shown below.
The syntax for accessing an individual character in a string is as shown below.
string_name[index]
where index is usually in the range of 0 to one less than the length of the string. The value
of index should always be an integer and indicates the character to be accessed.
For example,
>>> word_phrase = "be yourself"
>>> word_phrase[0]
'b'
>>> word_phrase[1]
'e'
>>> word_phrase[2]
''
>>> word_phrase[3]
'y'
You can also access individual characters in a string using negative indexing. If you have a
long string and want to access end characters in the string, then you can count backward
from the end of the string starting from an index number of −1. The negative index break-
down for the string “be yourself” assigned to word_phrase string variable
>>> word_phrase[-1]
'f'
>>> word_phrase[-2]
‘l'
String Slicing and Joining
The "slice" syntax is a handy way to refer to sub-parts of sequence of characters within an
original string. The syntax for string slicing is,
With string slicing, you can access a sequence of characters by specifying a range of index
numbers separated by a colon. String slicing returns a sequence of characters beginning
at start and extending up to but not including end. The start and end indexing values have
to be integers. String slicing can be done using either positive or negative indexing.
>>> healthy_drink = "green tea"
>>> healthy_drink[0:3]
'gre'
>>> healthy_drink[:5]
'green'
>>> healthy_drink[6:]
'tea'
>>> healthy_drink[:]
'green tea'
>>> healthy_drink[4:4]
''
>>> healthy_drink[6:20]
’tea'
Slicing can also be done using the negative integer numbers.
The negative index can be used to access individual characters in a string. Negative
indexing starts with −1 index corresponding to the last character in the string and then the
index decreases by one as we move to the left.
>>> healthy_drink[-3:-1]
'te'
>>> healthy_drink[6:-1]
'te'
Specifying Steps in Slice Operation
In the slice operation, a third argument called step which is an optional can be
specified along with the start and end index numbers. This step refers to the number of
characters that can be skipped after the start indexing character in the string. The default
value of step is one. In the previous slicing examples, step is not specified and in its
absence, a default value of one is used.
For example,
>>> newspaper = "new york times“
>>> newspaper[0:12:4]
'ny'
>>> newspaper[::4]
'ny e'
Python Code to Determine Whether the Given String Is a Palindrome or Not Using Slicing
def main():
user_string = input("Enter string: ")
if user_string == user_string[::-1]:
print(f"User entered string is palindrome")
else:
print(f"User entered string is not a palindrome")
if name == " main ":
main()
Joining Strings Using join() Method
Strings can be joined with the join() string. The join() method provides a flexible way to concatenate
strings. The syntax of join() method is,
string_name.join(sequence)
Here sequence can be string or list. If the sequence is a string, then join() function inserts string_name
between each character of the string sequence and returns the concatenated string. If the sequence is a
list, then join() function inserts string_name between each item of list sequence and returns the
concatenated string. It should be noted that all the items in the list should be of string type.
>>> date_of_birth = ["17", "09", "1950"]
>>> ":".join(date_of_birth)
'17:09:1950'
>>> social_app = ["instagram", "is", "an", "photo", "sharing", "application"]
>>> " ".join(social_app)
'instagram is an photo sharing application'
>>> numbers = "123"
>>> characters = "amy"
>>> password = numbers.join(characters)
>>> password
'a123m123y'
Split Strings Using split() Method
The split() method returns a list of string items by breaking up the string using the delimiter
string. The syntax of split() method is,
string_name.split([separator [, maxsplit]])
Here separator is the delimiter string and is optional. A given string is split into list of strings
based on the specified separator. If the separator is not specified then whitespace is
considered as the delimiter string to separate the strings. If maxsplit is given, at most maxsplit
splits are done (thus, the list will have at most maxsplit + 1 items). If maxsplit is not
specified or −1, then there is no limit on the number of splits.
>>> inventors = "edison, tesla, marconi, newton“
>>> inventors.split(",")
['edison', ' tesla', ' marconi', ' newton']
>>> watches = "rolex hublot cartier omega“
>>> watches.split()
['rolex', 'hublot', 'cartier', 'omega']
Strings Are Immutable
As strings are immutable, it cannot be modified. The characters in a string cannot be
changed once a string value is assigned to string variable. However, you can assign different
string values to the same string variable.
def main():
common_characters('rose', 'goose')
if __name__ == “__main__":
main()
Python Program to Count the Total Number of Vowels, Consonants and Blanks in a String
def main():
user_string = input("Enter a string: ")
vowels = 0
consonants = 0
blanks = 0
for each_character in user_string:
if(each_character == 'a' or each_character == 'e' or each_character == 'i' or
each_character == 'o' or each_character == 'u'):
vowels += 1
elif "a" < each_character < "z":
consonants += 1
elif each_character == " ":
blanks += 1
print(f"Total number of Vowels in user entered string is {vowels}")
print(f"Total number of Consonants in user entered string is {consonants}")
print(f"Total number of Blanks in user entered string is {blanks}")
if __name__ == “__main__":
main()
Python Program to Calculate the Length of a String Without Using Built-In len() Function
def main():
user_string = input("Enter a string: ")
count_character = 0
for each_character in user_string:
count_character += 1
print(f"The length of user entered string is {count_character} ")
if __name__ == “__main__":
main()
String Methods
You can get a list of all the methods associated with string by passing the str
function to dir().
>>> dir(str)
[' add ', ' class ', ' contains ', ' delattr ', ' dir ', ' doc ', ' eq ', ' format ', ' ge ',
' getattribute ', ' getitem ', ' getnewargs ', ' gt ', ' hash ', ' init ', ' init_subclass ', ' iter ',
' le ', ' len ', ' lt ', '
mod ', ' mul ', ' ne ', ' new ', ' reduce ', ' reduce_ex ', ' repr ', ' rmod ', ' rmul ',
' setattr ', ' sizeof ', ' str ', ' subclasshook ', 'capi- talize', 'casefold', 'center', 'count',
'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha',
'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle',
'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust',
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate',
'upper', 'zfill']
For example,
>>> fact = "Abraham Lincoln was also a champion wrestler"
>>> fact.isalnum()
False
>>> "sailors".isalpha()
True
>>> "2018".isdigit()
True
>>> fact.islower()
False
>>> "TSAR BOMBA".isupper()
True
>>> "columbus".islower()
True
>>> warriors = "ancient gladiators were vegetarians"
>>> warriors.endswith("vegetarians")
True
>>> warriors.startswith("ancient")
True
>>> warriors.startswith("A")
False
>>> warriors.startswith("a") True
>>> "cucumber".find("cu") 0
>>> "cucumber".find("um") 3
>>> "cucumber".find("xyz")
-1