Loop Control Statements in C Introduction to HTML How to use the Github API The image tag, anchor tag and the button tag Ordered and Unordered Lists in HTML The division tag HTML Forms Tables in HTML Introduction to C Programming Introduction to Python Varibles and Datatypes in Python Operators in Python Typecasting in Python Input and Output in Python If Else in Python Loops in Python Break, Continue and Pass in Python Python practice section 1 Lists in Python Tuple in Python

Strings in python

String is basically a sequence of characters. For example, we have a string "rapid", this string is sequence of characters('r', 'a', 'p', 'i', 'd'). We have string as a datatype in Python.

Defining string

In Python we can define a string in three ways:

  1. Using single quotes : name = 'Rapid'
  2. Using double quotes : name = "Rapid"
  3. Using triple quotes : name = '''Rapid'''
We mainly use triple quotes to define a multi-line string.

# using single quotes
name1 = 'rapid'
print('using single quotes')
print(type(name1))
print(name1)
print()

# using double quotes
name2 = "rapid"
print("using double quotes")
print(type(name2))
print(name2)
print()

# using triple quotes
name3 = '''We use 
triple quotes
to define a multi-line string.'''
print('''using triple quotes''')
print(type(name3))
print(name3)
print()

Output

using single quotes
<class 'str'>
rapid

using double quotes
<class 'str'>
rapid

using triple quotes
<class 'str'>
We use 
triple quotes
to define a multi-line string.
                

F-strings

F-strings provide an efficient way to insert variables and expressions in strings.

Syntax:
f_string = f"string"
Consider following code:

str1 = f"this is f-string"
print(str1)
print()

name = "akshay"
str2 = f"My name is {name}"
print(str2)
print()

var1 = 2
var2 = 3
str3 = f"{var1} + {var2} = {var1+var2}"
print(str3)
    

Output

this is f-string

My name is akshay

2 + 3 = 5         

Indexing in string

In Python every character of a string has a unique index or we can say unique position. Index is basically position of a specific character from left. The first character of string has index 0, second character has index 1 and so on. With the help of index, we can access characters present at a specific index.

String = "rapid"
Character Index
r 0
a 1
p 2
i 3
d 4

Negative indexing in string

We have seen indexing above, all indexes are positive and position is considered from left. Negative index is basically the position of a character from right. In this case index of last character is -1 (zero is not a negative number), index of second last character is -2, and so on.

String = "rapid"
Character Index
r -5
a -4
p -3
i -2
d -1

String slicing

Slicing means getting a part of a string or we can say getting a subsequence from a string. For slicing in Python we use Square brackets.

Syntax:
substing = string[start index : end index]

  • start index is included in substring
  • end index is not included in substring
  • Consider following code for better understanding:
    
    string = "rapid"
    
    print("Slicing from index 0 to index 3")
    print(string[0:3])
    print()
    
    print("Slicing from index 1 to index 4")
    print(string[1:4])
    print()
    
    print("Slicing from index 2 to last")
    # If we are not providing end index then it will slice till last
    print(string[2:])
    print()
    
    print("Slicing from start to index 3")
    # If we are not providing start index then it will start slicing from index 0
    print(string[:3])
    print()
    
    

    Output:

    Slicing from index 0 to index 3
    rap
    
    Slicing from index 1 to index 4
    api
    
    Slicing from index 2 to last
    pid
    
    Slicing from start to index 3
    rap
    
    

    String Slicing with skip value

    While performing slicing we can define skip value. Skip value means which character will be selected after the current character. By default, the skip value is one, due to this all characters are selected from the start index to the end index.

    Let us understand skip value with the example:
    Example 1:
    string = akshay
    skip value = n = 1
    Here we select first character, 'a' then we select next nth character that is 'k' (as n is 1).
    Or we can say we will skip (n-1) characters and select nth character.
    Here we will get "akshay" as result.
    
    Example 2:
    String = rapid
    skip value = n = 2
    Here we select first character, 'r' then we select next nth character that is 'p' (as n is 2).
    Or we can say we will skip (n-1) characters and select nth character.
    Now we are at 'p', we will again skip (n-1) characters and select nth character that is d.
    Here we will get "rpd" as result.
    
    Syntax:
    substing = string[start index : end index : skip value]
    
    
  • start index is included in substring
  • end index is not included in substring
  • skip value is number of characters we need to skip
  • Consider following code for better understanding:
    
    string = "rapid"
    
    print("Slicing from index 0 to index 3 with skip value = 1")
    print(string[0:4:1])
    print()
    
    print("Slicing from index 0 to index 3 with skip value = 2")
    print(string[0:4:2])
    print()
    

    Output:

    Slicing from index 0 to index 3 with skip value = 1
    rapi
    
    Slicing from index 0 to index 3 with skip value = 2
    rp
        
    

    String functions

    1. String.count('x'): This function is used to find total number of occurrence of any character.
    2. String.capitalize(): It converts the first character of a string to uppercase.
    3. String.endswith("string2"): It returns true if string ends with "string2".
    4. String.find("str"): It returns the first index of occurrence of "str".
    5. String.isalnum(): It returns true if all characters of string are alphanumeric.
    6. String.isalpha(): It returns true if all characters of string are alphabet.
    7. String.isdigit(): It returns true if all characters of string are digits.
    8. String.islower(): It returns true if all characters of string are lowercase.
    9. String.isupper(): It returns true if all characters of string are uppercase.
    10. String.lower(): It convert string into lowercase.
    11. String.upper(): It convert string into uppercase.
    12. String.replace(old_word, new_word): It replace all old_word with new_word in entire string.
    13. String.split(): It splits a string at a specific separator and returns a list. By default space is separate.
    14. String.lstrip(): It removes all spaces from begin and end of string. If we provide any character then it will remove that character instead of space. Example: String.lstrip("a").
    Consider following code for better understanding:
    
    string = "rapid coders"
    print("string = ",end="")
    print(string)
    print()
    
    print("string.count('a') = ", end="")
    print(string.count('a'))
    print()
    
    print("string.capitalize() = ", end="")
    print(string.capitalize())
    print()
    
    print("string.endswith('coders') = ", end="")
    print(string.endswith('coders'))
    print()
    
    print("string.find('pi') = ", end="")
    print(string.find('pi'))
    print()
    
    print("string.isalnum() = ", end="")
    print(string.isalnum())
    print()
    
    print("string.isalpha() = ", end="")
    print(string.isalpha())
    print()
    
    print("string.isdigit() = ", end="")
    print(string.isdigit())
    print()
    
    print("string.islower() = ", end="")
    print(string.islower())
    print()
    
    print("string.isupper() = ", end="")
    print(string.isupper())
    print()
    
    print("string.upper() = ", end="")
    print(string.upper())
    print()
    
    print("string.lower() = ", end="")
    print(string.lower())
    print()
    
    print('string.replace("coders", "akshay") = ', end="")
    print(string.replace("coders", "akshay"))
    print()
    
    print("string.split() = ", end="")
    print(string.split())
    print()
    
    print("string.lstrip() = ", end="")
    print(string.lstrip())
    print()
        
    

    Output:

    string.capitalize() = Rapid coders
    
    string.endswith('coders') = True
    
    string.find('pi') = 2
    
    string.isalnum() = False
    
    string.isalpha() = False
    
    string.isdigit() = False
    
    string.islower() = True
    
    string.isupper() = False
    
    string.upper() = RAPID CODERS
    
    string.lower() = rapid coders
    
    string.replace("coders", "akshay") = rapid akshay
    
    string.split() = ['rapid', 'coders']
    
    string.lstrip() = rapid coders