Definition of Strings in Python with its Examples

string-in-python
  • Save

Are you tired of looking for the best answer to what string means in Python? Don’t worry; in this blog I will tell you about: What are strings in Python. What are the built-in string functions in Python? Some important tips about strings in Python are explained with the help of code. So let’s get started with the blog.

Table of Contents

Introduction to Strings in Python

Strings in Python is a sequence of characters.

Computers only understand binary language i.e 0’s and 1’s. So even though you may see characters on your screen, internally it is stored and manipulated as a combination of 0s and 1s.

A string is a sequence of Unicode characters. Unicode is the universal character representation standard for text in computer processing. It is a way of encoding multilingual plain text making it easier to exchange text files internationally.

Strings can be created simply by enclosing characters in single or double quotes.

## Example of String
company_name = "Bin-Fin Tech"

Strings in Python are mutable or immutable?

The string is not mutable in Python. Strings are immutable datatypes which means that their value cannot be updated.

# String immutable Example
company = "Bin-Fin"
print(id(company))

Output:
140192050639216

# Let's update the first index of company variable
company[1] = "o"

# Output Error:
Traceback (most recent call last):
   File "stringDem.py", line 12, in <module>
     company[1] = "o"
TypeError: 'str' object does not support item assignment


# Now let's update the whole string with comapny variable
company = "Tech"
print(company)
print(id(company))

Output:
Tech
140192050639408

Now, I will explain the above code which clears all myths about whether a string is mutable or immutable.

First I assign the value of “Bin-Fin” in the variable “company”. This stores the value at the address “140192050639216”, which we can see in line 4. id() function returns the address of the value where he is stored.

Now, when I am updating the single value of a variable “company” at 1st position company[1], it returns the Type Error stating that the ” ‘str’ object does not support item assignment “.

Now, I am reassigning the value of the company, not updating the value note properly, the new value I am storing Tech in the company variable. The value and address of the company variable have fully changed.

String is mutable or immutable
  • Save
The string is mutable or immutable

Operations that can be performed on Strings in Python:

A) Create Strings in Python:

In Python, strings can be created by using single, double, or even triple quotes.

# Creating a string
# Single quotes
company = 'Bin-Fin'

# Double Quotes
company = "Bin-Fin"

# Triple Quotes
company = '''Bin Fin
            helps learner to go in the field
            of programming.'''

B) Accessing Characters of Strings in Python:

In Python, accessing characters can easily be achieved by indexing.

If the index is out of range then it will return an Index Error.

# accessing characters in Python string

company = "Bin-Fin"

print(company[0])

# Output:
B

print(company[-1])
#Output:
n

print(company[20])

# Output:
Traceback (most recent call last):
  File "stringDem.py", line 42, in <module>
    print(company[20])
IndexError: string index out of range

print(company["j"])

#Output
Traceback (most recent call last):
  File "stringDem.py", line 45, in <module>
    print(company["j"])
TypeError: string indices must be integers

In Indexing, we have to provide the index of the characters we want as an output.

If you provide a negative number it will start the count from the last characters of the string.

In the Indexing part, you should only provide the Int datatype number, Otherwise, it will return a Type Error.

c) Slicing of Strings in Python:

Slicing of Strings in Python is used to access a range of characters of the String.

It is done by using the operator’s colon (:).

# Slicing in Python

company_name = "Bin-Fin Tech"

1) print(company_name[2:8])  

#Output:
n-Fin

2) print(company_name[:])  

 
#Output:
Bin-Fin Tech

3) print(company_name[1:])  

#Output:
in-Fin Tech

4) print(company_name[:8]) 
 
#Output:
Bin-Fin

5) print(company_name[:22])  

#Output:
Bin-Fin Tech

6) print(company_name[2:-1])  

#Output:
n-Fin Tec

For example, no:1, which starts from position 2 and ends at position 7 is less than 8.

In an example, no:2, If starting and ending do not mention it means that it will read all the string characters.

For example, no:6, position -1 means that it starts from the last position characters i.e. (h)

So it means that it starts from position 2 and ends at position -2.

d) Reverse of Strings in Python:

We can reverse the strings in Python by using the double colon operator (::).

# Reversing the String

company_name ="Bin-Fin Tech"

print(company_name[::-1])

#Output:

hceT niF-niB

e) Updating or Deleting the characters of Strings in Python:

As you know that string is immutable means that we can not update that variable once the variable is assigned. Although we can delete the entire string with the help of the built-in keyword del. We can reassign the value of the same variable name.

# Updating or Deleteing the value

company_employee = "Vicky Kumar"

1) company_employee[0] = "J"
print(company_employee)

#Output:
Traceback (most recent call last):
  File "stringDem.py", line 72, in <module>
    company_employee[0] = "J"
TypeError: 'str' object does not support item assignment


company_update_employee = company_employee.replace('V', 'M')
print(company_update_employee)

Output:
Micky Kumar

The above example shows that I want to update the employee name but implementing by 1st way it gives an error while using 2nd way we achieve this by adding a new variable.

# Updating or Deleteing the value

company_employee = "Vicky Kumar"

print(company_employee)

del company_employee

print(company_employee)

Output:

Vicky Kumar

Traceback (most recent call last):
  File "stringDem.py", line 82, in <module>
    print(company_employee)
NameError: name 'company_employee' is not defined

The above example shows how the del keyword deletes the variable from the memory, and while printing the second time it returns an error.

f) Concatenation of Strings in Python:

We can concatenate strings with the help of the plus operator (+).

# Concatenate two strings
company = "Bin-Fin"
name = "Tech"
print(company+name)

Output:
Bin-FinTech

g) Repetition of Strings in Python:

We can repeat the string n times with the help of the asterisk operator (*).

Syntax: string_var * (n times)

# Repetition
print("Bin-Fin " * 3)

Output:
Bin-Fin Bin-Fin Bin-Fin

h) Membership in Python Strings:

In the Membership operation, we can validate whether this particular character is present or not.

It returns a boolean value. We use two keywords in membership operation, in and not in.

company_name = "Bin-Fin"

print('i' in company_employee)
Output:
True

print('q' in company_employee)
Output:
False

print('n' not in company_name)
Output:
False

print('q' not in company_name)
Output:
True

Now, we have almost completely finished what operations we can perform on Python’s String.

Now we have to learn some important Python’s String in-built functions. So let’s get started.

Python built-in functions of Strings in Python:

a) lower():

It converts the string into small letters.

print("BinFin Tech".lower())

Output:
binfin tech

b) upper():

It converts the string into capitalization format.

print("Bin Fin".upper())

Output:
BIN FIN

c) split():

It returns the list of strings in array format. Counting each string one element in the array.

print("Bin Fin Tech".split())

Output:
['Bin', 'Fin', 'Tech']

d) count(character):

It returns the number of occurrences of the character in the string.

print("Bin Fin".count("i"))

Output:
2

e) replace(old_character,new_character):

It replaces the older character with the new character.

It is case-sensitive means ‘w’ and ‘W’ are different characters.

Syntax: replace(older_character,new_character)

print("Win Bin".replace('W', 'F'))

#Output:
Fin Bin

f) startswith(character):

It accepts one argument which tells whether the string starts with that character or not.

It returns a boolean value.

print("Win Fin".startswith('B'))

Output:
False

What are Strings in Python?

Strings in Python is a sequence of characters.
Computers only understand binary language i.e 0’s and 1’s. So even though you may see characters on your screen, internally it is stored and manipulated as a combination of 0s and 1s.
A string is a sequence of Unicode characters. Unicode is the universal character representation standard for text in computer processing. It encodes multilingual plain text, making it easier to exchange text files internationally.

Strings in Python are mutable or immutable?

The string is not mutable in Python. Strings are immutable datatypes which means that their value cannot be updated.

Some of the examples of the String built-in function?

print(“Win Fin”.startswith(‘B’))
Output:
False

print(“Win Bin”.replace(‘W’, ‘F’))
Output:
Fin Bin

print(“Bin Fin”.count(“i”))
Output:
2

print(“Bin Fin Tech”.split())
Output:
[‘Bin’, ‘Fin’, ‘Tech’]

Write blogs related to Ethical hacking, Computer networks, Linux, Penetration testing and Web3 Security.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top
0 Shares
Share via
Copy link