4. Strings

Syllabus :

Manipulating Strings: Working with Strings, Useful String Methods, Format operators

4.1 Working with Strings :

A string is a sequence of characters. It can be created by enclosing characters in single or double or triple quotes.

Example : ‘Hello World!’ , “Python Programming“ ,   ”’apple”’

Creating a string :

Creating a string is as simple as assigning a value to variables as illustrated below :

 var1 = 'Hello World!' 
 var2 = "Python Programming"
 var3 = '''Water Melon'''

Triple quotes can extend multiple lines as illustrated below :

Length of a string

One can get last letter of string using len( ) function as illustrated below :

String Indexing

In Python string can be indexed in forward( start to end) and backward(end to start) direction as illustrated in the figure below :

Consider a string name = ” Sophia“. Here string Sophia is made up of 6 characters. Each character of the string can be accessed by using either forward indexing or backward indexing as illustrated below:

String Traversal

String traversal can be performed Using looping statements like for loop and while loop .

String traversal using while loop

String traversal using for loop

String traversal in reverse order

Lists aren’t the only data types that represent ordered sequences of values.For example, strings and lists are actually similar, if you consider a string to be a “list” of single text characters. Many of the things you can do with lists  can also be done with strings: indexing; slicing; and using them with for loops, with len(), and with the in and not in operators.

String Slices :

A segment of a string is called a slice. Selecting a slice is similar to selecting a character.

  • The : operator in slicing [n:m] returns the part of the string from the “n-eth” character to the “m-eth” character, including the first but excluding the last.
  • If you omit the first index (before the colon), the slice starts at the beginning of the string.
  • If you omit the second index, the slice goes to the end of the string:
    • fruit = ‘banana’
    • fruit[:3]  gives ‘ban’
    • fruit[3:]  gives ‘ana’
  • If the first index is greater than or equal to the second the result is an empty string, represented by two quotation marks:
  • fruit = ‘banana’
  • fruit[3:3]     gives  ‘ ‘
  • An empty string contains no characters and has length 0, but other than that, it is the same as any other string.

Slicing Example

Strings are immutable

Strings are immutable. That means the characters of a string cannot be changed. String cannot have values added , removed or changed once created. As illustrated in the following example, after assigning the value “Hello Python” to greetings, if any attempt is made to mutate or change the values, Type error will be generated.

The proper way to ‘mutate‘ a string is to slice and concatenate to build a new string by copying from parts of the old string as illustrated below :

Example : Looping and Counting

Example : usage of in operator for strings

String Comparison using ==,< and > operators

Code Snipped

Output 1:

Output 2:

Output 3:

4.2 Useful String methods

Strings are an example of Python objects. An object contains both data ( the actual string itself ) and methods which are effectively functions that are built into the object and are available to any instance of the object.

Using the command dir(str) one can list all the methods supported by python as illustrated below:

Table : String Methods and Description

MethodDescription
capitalize()Converts the first character to upper case
casefold()Converts string into lower case
center()Returns a centered string
count()Returns the number of times a specified value occurs in a string
encode()Returns an encoded version of the string
endswith()Returns true if the string ends with the specified value
find()Searches the string for a specified value and returns the position of where it was found
index()Searches the string for a specified value and returns the position of where it was found
isalnum()Returns True if all characters in the string are alphanumeric
isalpha()Returns True if all characters in the string are in the alphabet
isdigit()Returns True if all characters in the string are digits
isidentifier()Returns True if the string is an identifier
islower()Returns True if all characters in the string are lower case
isnumeric()Returns True if all characters in the string are numeric
isspace()Returns True if all characters in the string are whitespaces
istitle()Returns True if the string follows the rules of a title
isupper()Returns True if all characters in the string are upper case
ljust()Returns a left justified version of the string
lower()Converts a string into lower case
lstrip()Returns a left trim version of the string
replace()Returns a string where a specified value is replaced with a specified value
rjust()Returns a right justified version of the string
rsplit()Splits the string at the specified separator, and returns a list
rstrip()Returns a right trim version of the string
split()Splits the string at the specified separator, and returns a list
startswith()Returns true if the string starts with the specified value
strip()Returns a trimmed version of the string
swapcase()Swaps cases, lower case becomes upper case and vice versa
title()Converts the first character of each word to upper case
upper()Converts a string into upper case
[Source : https://www.w3schools.com/python/python_ref_string.asp]

capitalize() : Converts the first character to upper case

Example : Capitalize

Example : Title and Capitalize

lower()

upper()

casefold(): Converts string into lower case

Example :

center() : Returns a centered string

swapcase()

find()

count( ):

strip(), lstrip() and rstrip()

startswith() and endswith()

split()

join()

ASCII VALUES

To print ASCII character for given ASCII Value:

4.3 Python String Operators

Operators : +, * , [ ] slicing , Range Slicing [ :] , Membership operators : in and not in , iterating operators : for , Rawstring : r/R

4.3.1 String Concatenation using + :

4.4 Format Operators

Format operators are used in print statement . There are two format operators :

  1. %
  2. format()

4.4.1. % operator:

Syntax :

print("%s1  %s2  %s3 ------"%(arg1,arg2,arg3,------argn)) 

Here, 
    s1,s2 ,..........sn are conversion specifiers like d(for int ),f(for float),s(for string) ,etc. 
and 
    arg1,arg2....argn are variables or values .
Example 

4.4.2 : format() function

Syntax :

print('{0} {1} ......{n}'.format(agr1,agr2,agr3....argn)
Here,
    0,1,2,------are position specifiers  
and 
    arg1,arg2,-----argn are variables/values.

Example :

Sample Programs:

1.Write a Python Program to Check if the String is Symmetrical or Palindrome:

A string is said to be symmetrical if both halves of the string are the same, and a string is said to be a palindrome if one half of the string is the opposite of the other half or if the string appears the same whether read forward or backward.

Output 1 :

Output 2

2. Write a Python Program to find the length of string

Output :

3. Write a Python Program to Count the Number of Digits, Alphabets, and Other Characters in a String

Output :

4. Write a Python Program to Count the Number of Vowels in a String

5. Write a Python Program to Split and Join a String

6. Write a Python program to display a largest word from a string

7. Write a Python program to display unique words from a string

8. Write a Program to accept a word and display a ASCII value of each character of words

Questions for Practice:

  1. Define String? Explain at least 5 String functions with examples.
  2. Write a python program to display presence of given substring in main string.
  3. Define Tuple , List , Strings and Dictionary in Python.
  4. List any six methods associated with string and explain each of them with example.
  5. Write a Python program to swap cases of a given string .
    • Input : Java
    • Output : jAVA
  6. Explain the various string methods for the following operations with examples.
    • Removing white space characters from the beginning end or both sides of a string
    • To right -justify , left justify and center a string
  7. What are escape characters?
  8. What do the \n and \t escape characters represent?
  9. How can you put a \ backslash character in a string?
  10. The string value “Howl’s Moving Castle” is a valid string. Why isn’t it
    a problem that the single quote character in the word Howl’s isn’t
    escaped?
  11. If you don’t want to put \n in your string, how can you write a string
    with newlines in it?
  12. What do the following expressions evaluate to?
    • ‘Hello world!'[1]
    • ‘Hello world!'[0:5]
    • ‘Hello world!'[:5]
    • ‘Hello world!'[3:]
  13. What do the following expressions evaluate to?
    • • ‘Hello’.upper()
    • • ‘Hello’.upper().isupper()
    • • ‘Hello’.upper().lower()
  14. What do the following expressions evaluate to?
    • • ‘Remember, remember, the fifth of November.’.split()
    • • ‘-‘.join(‘There can be only one.’.split())
  15. What string methods can you use to right-justify, left-justify, and center a string?
  16. How can you trim whitespace characters from the beginning or end of
    a string?
  17. Write a Python program to calculate the length of a string.
  18. Write a program to check if the letter ‘e’ is present in the word ‘Umbrella’.
  19. Write a program to check if the word ‘orange’ is present in the “This is orange juice”.
  20. Write a program to find the first and the last occurence of the letter ‘o’ and character ‘,’ in “Hello, World”.
  21. Write a program that takes your full name as input and displays the abbreviations of the first and middle names
  22. except the last name which is displayed as it is. For example, if your name is Robert Brett Roser, then the output should be R.B.Roser.
  23. Write a program to find the number of vowels, consonents, digits and white space characters in a string.
  24. Write a program to make a new string with all the consonents deleted from the string “Hello, have a good day”
  25. Write a Python program to count the number of characters (character frequency) in a string.
  26. Write the string after the first occurrence of ‘,’ and the string after the last occurrence of ‘,’ in the string “Hello, Good, Morning”. World”.
  27. Write a program to print every character of a string entered by user in a new line using loop.
  28. Write a program to find the length of the string “refrigerator” without using len function.
  29. Write a program to check if the letter ‘e’ is present in the word ‘Umbrella’.
  30. Write a program to check if the word ‘orange’ is present in the “This is orange juice”.
  31. Write a program to find the first and the last occurence of the letter ‘o’ and character ‘,’ in “Hello, World”.
  32. Write a program that takes your full name as input and displays the abbreviations of the first and middle names except the last name which is displayed as it is. For example, if your name is Robert Brett Roser, then the output should be R.B.Roser.
  33. Check the occurrence of the letter ‘e’ and the word ‘is’ in the sentence “This is umbrella”.
  34. Write a program to find the number of vowels, consonents, digits and white space characters in a string.
  35. Write a program to make a new string with all the consonents deleted from the string “Hello, have a good day”.