Thursday, October 8, 2020

thumbnail

Strings in Python | @codeakey

In this blog post, we will get into the following topics...

Contents:

    1) Basic of Strings
    2) Operations in Strings
    3) Built-In Functions in String
    4) Example in another blog Link: Click Here


Basics of Strings

    Definition:
            Strings are the collection of characters.

    You start your programming journey using String. as 
print("Hello World!")
    Strings are one of the most important Data Structures in Python.
    
    In the above Python Program, the statement inside double quotations are nothing but the strings.

    The part to note here is: Strings can be inside any of the quotations i.e., single(' '), double(" ") or triple(''' ''').
    
    The string inside triple quotation ('''---''') is usually, multiline strings as shown below.

print('''This is great
        Python is intresting language
        Subscribe to eat(); sleep(); code(); repeat();
        Go to YouTube video also ''')

Strings are Sequence...

    Alike other data structures in Python (like Tuples, Dictionary, List), String is also be considered as Sequence.
    
    That is, Strings are as a sequence of characters.
   
    And all sequence types are indexed with indices starting at 0. Strings are a sequence of characters stored in consecutive memory locations; for example, the string 'hello' can be pictured as in Fig.

As you can see in the figure above, it shows the indexing of the elements in the string in forward as well as reverse direction. 
    
    Point to note: In the forward direction, the indexing starts from 0, not 1, and in the reverse direction, indexing starts from -1 but not from 0.

    Indexing also makes it easy to get access to the elements. (which we will see in a further post)

Assigning String to a Variable

    Assigning a string to a variable is the same as assigning an integer value to a variable, but the only difference is we use quotations. The code below shows how:
a = "hello world"            # here variable a is assigned to the string "hello world"

Strings are immutable

    The property of string which makes it as different from all other data structures is immutability. That means string once created cannot be modified, in the same memory location. It leads to an error if we try to do so. In Python Tuples also have the same property. The property of immutability makes strings a secure datatype. The program below shows how it happens...
wishMe = "Good Morning"
wishMe[0] = 'H'                # this will leat to ERROR
print(wishMe)                    # it will print 'Good Morining'
 This is the end of the 1st section: Basic of Strings.
You can refer to the video below...

Operation on Strings 

    The following table would help you to understand different operations on strings...

    
    Let's into getting some coding part to understand the concept:

---# string operations 
str1 = "Python is Interesting, "
# s[i]
print(str1[10])
print(str1[15])
# s[i:j]        j=j-1
print(str1[0:15])     # 15-1
print(str1[:20])
print(str1[:])
print(str1[:100])
print(str1[20:50])
# s[i:j:k]
print(str1[1:7:2])
print(str1[::3])
# s + t
str2 = " and fun"
str3 = str1 + str2
print(str3)
# s += t
str2 += str3
print(str2)
# s * n
str4 = str1 * 3
print(str4)
# len(s)
print(len(str4))
# max(s)
print(max(str1)
# min(s)
print(min(str2))
# x in s
x = "on"
print(x in str1)
# x not in s
print(x not in str1)
Output:
i
e
Python is inter
Python is interestin
Python is interesting, 
Python is interesting, 
g, 
yhn
Ph  tei,
Python is interesting,  and fun
 and funPython is interesting,  and fun
Python is interesting, Python is interesting, Python is interesting, 
69
y
 
True
False

This is the end of the 2nd section: Operations on Strings.

You can refer to the video below...




Built-In Functions on Strings

There's a particular syntax in which we the functions in the string are declared which is as below:

string_name.function()
eg. str1.capitalize()

I have categorized, built-in functions as:
1) Converting String Functions
2) Formatting String Functions
3) Testing String Functions
4) Searching String Functions

1) Converting String Functions

capitalize()                     --     only first character is capitalized

lower()                               --     all the character converted to lower case

upper()                                  --     all the character are converted to upper case

title()                                  --     the first character of all words in a capital case

swapcase()                           --     lowercase is converted to uppercase and vice versa

replace(old, new)          --     replaces the old string with a new string

Example:
str = "Python is interesting"
print(str.capitalize())
print(str.lower())
print(str.upper()
print(str.title())
print(str.swapcase())
Output:
Python is interesting
python is interesting
PYTHON IS INTERESTING
Python Is Interesting
PYTHON IS INTERESTING

2) Formatting String Functions

center(width)        --     returns a string in a field of the given width

ljust(width)         --     returns a string left-justified in a field of a given width

rjust(width)         --     returns a string right-justified in a field of a given width

format()             --     formats string (look at the example below)

Example:
str = "python"
print(str.center(20))
print(str.ljust(20))
print(str.rjust(20))
Output:
       python       
python              
              python

3) Testing String Functions:

isalnum()            --     returns True if all character in strings are alphanumeric and there is at least one character and False otherwise

isalpha()            --     returns True if all character in a string are alphabets and False otherwise

isdigit()            --     returns True if all the character in the string are numbers False otherwise

islower()            --     returns True if all the character in the string is in lowercase False otherwise

isupper()                         --    returns True if all the character in the string is in uppercase False otherwise

isspace()                            --    returns True if there is only space else False

Example:
str = "python"
print(str.isalpha())
print(str.isalnum())
print(str.isdigit())
print(str.islower())
print(str.isupper())
print(str.isspace())
Output:
True
False
False
True
False
False

4) Searching String Function

endswith("substring)       --    returns True if the string ends with the substring

startswith("substring")  --    returns True id the string starts with the substring

find("substring")                   --    returns True lowest index or -1 if the substring not found

count("substring")       --    returns True number of occurrence of the string


Example:
str = "python"
print(endswith("on"))
print(startswith("ph"))
print(find("hon"))
print(count("h"))
Output:
True
False
-1
1

This is the end of the 3rd section: Built-in functions in String.

You can refer to the video below...


Subscribe to my YouTube channel for more tutorial videos...

So, this is it, in the next blog I will be discussing more format() function. Till then.
Take Care...
and Stay Safe.

It's Harsh Jaiswal
Signing off...




    

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

Sieve Of Eratosthenes | Mathematics | Data Structures and Algorithm | Python

Problem Statement: The  Sieve of Eratosthenes  is a method for finding all primes up to (and possibly including) a given natural n . n .  Th...