Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Creating Strings in Python
2.1.
Single Line Strings
2.2.
Multi-Line Strings
3.
Accessing characters of the String
3.1.
Accessing Single Character
3.2.
Accessing Multiple Characters: Slicing
4.
String Length
5.
Looping Through a String
6.
Deletion in a String
6.1.
Deleting a character
6.2.
Deleting an entire string:
7.
Updation in a String
7.1.
Updating a character in the string.
7.2.
Updating an entire string:
8.
Repeat a String
9.
Formatting of Strings
10.
FAQs
11.
Key Takeaways
Last Updated: Mar 27, 2024

Strings in Python

Author GAZAL ARORA
0 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

The text type in programming is often called string and, in Python, just str. A string is known as a sequence of characters. A character is nothing but a symbol. For example, A, B, C, '1', '.', '@', etc, are characters and "ABC", "123" are strings.

Computers work with binary numbers (0,1) instead of characters. Even though you see characters on your screen, they are saved and modified inside as a series of 0s and 1s.

The process of converting a character to a number is known as encoding, and the reverse procedure is known as decoding. Some of the most used encodings are ASCII and Unicode.

In Python, Strings are arrays of bytes that represent Unicode characters.

Python does not contain any character variables compared to other programming languages. In Python, characters are instead strings of unit length.

Also see, Merge Sort Python

Creating Strings in Python

Single Line Strings

A string in Python is surrounded by either single quotation marks or double quotation marks. E.g., 'Coding Ninjas' is the same as "Coding Ninjas."

# Creating and printing strings with single quotation marks.
string1 = 'Hello Ninjas'
print(string1)

# Creating strings with double quotation marks.
string2 = "Welcome to Coding Ninjas"
print(string2)

# Printing directly.
print('Hello Ninjas')
print("Welcome to Coding Ninjas")

 

Output:

Multi-Line Strings

You can use three quotes to declare a multi-line String in Python.

# Creating and printing multi-line strings with triple quotation marks.

 

string1 = '''Hello Ninjas,
Welcome to Coding Ninjas'''


print(string1)

 

Output:

Check this out: Fibonacci Series in Python

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Accessing characters of the String

Accessing Single Character

Since strings are like arrays, individual characters can be accessed using Indexing. The index must be an integer, and it starts from 0. 

Python also supports negative Indexing. The index value of -1 denotes the last item, the index of -2 the second last item, and so on. 

Trying to access a character outside the index range will result in an IndexError.
 

string = "Coding Ninjas"
print("Original String: ")
print(string)

# Printing 1st character.
print("\nFirst character of the string is: ")
print(string[0])

# Printing the last character.
print("\nLast character of the string is: ")
print(string[-1])

 

Output:

You can practice by yourself with the help of online python compiler for better understanding.

Accessing Multiple Characters: Slicing

The slicing method is used to access a range of characters in the String. A Slicing operator is used to slice a String (colon).

For example, 

String = “Coding Ninjas”

To print the characters odi of Coding Ninjas, 

we have to use: print(String[1:4]). 

string = "Coding Ninjas"
print("Original String: ")
print(string)

# Printing odi.
print("\nPrinting odi")
print(string[1:4])

# Printing characters between 2rd to 10th index.
print("\nPrinting characters between 2rd to 10th index:")
print(string[2:10])

# Printing characters between 3rd and the last character.
print("\nPrinting characters between 3rd and the last character:")
print(string[2:-1])

 

 

Output:

String Length

Python provides the len() method to determine the length of a string.

string = "Coding Ninjas"
print("Original String: ")
print(string)

print("\nLength of the string 'Coding Ninjas' is: ")
print(len(string))

 

Output:

Looping Through a String

Since strings are arrays, we can use a for loop to traverse through the characters in a string.

string = "Ninjas"
print("Original String: ")
print(string)

forin string:
  print(x)

 

Output:

Deletion in a String

The deletion of characters from a string is not allowed in Python. This will result in an error since the deletion of an item from String are is not supported. However, the entire String can be deleted with the built-in del Keyword.

Deleting a character

For example, deleting a character with index 2 from string "Coding Ninjas".

string = "Coding Ninjas"
print("Original String: ")
print(string)

del(string[2])
print(string)

 

Output

Deleting an entire string:

string = "Coding Ninjas"
print("Original String: ")
print(string)

del(string)
print(string)

 

Output:

Updation in a String

The updation of characters from a string is not allowed in Python. This will result in an error since the updation of an item from String are is not supported. Since strings are immutable, elements of a String cannot be modified after being assigned. Only new strings can be reassigned to the same name.

Updating a character in the string.

For example, updating a character with index 2 to ‘a’.

string = "Coding Ninjas"
print("Original String: ")
print(string)

string[2] = 'a'
print(string)

 

Output:

Updating an entire string:

 

string = "Coding Ninjas"
print("Original String: ")
print(string)

print("\nModified String: ")
string = 'Welcome Ninjas'
print(string)

 

Output:

Repeat a String

Use the * symbol to repeat a string.

string = 'Coding'
string = string * 3
print(string)

 

Output:

Also see, Python Filter Function

Formatting of Strings

Python also provides the format() function, a very versatile and powerful tool for formatting Strings. To set the order, the Format method in String uses curly braces {} as placeholders that can hold arguments based on position or keyword.

Syntax:

"Any sentence {variable1} some text {variable2}".format(variable1 = "DATA", variable1 = "DATA")

 

For example,

name = ["John""Aarti""Rahul""Karan"]
age = [20, 22, 21, 25]

forin range(4):
  print("Hi, My name is {var1} and I am {var2} years old.".format( var1 = name[i], var2 = age[i]))

 

Output:

Check out Escape Sequence in Python

FAQs

 

Q1:What are strings in Python?
Ans: A string is a sequence of alphabets, words, or other characters. It is a simple data structure that serves as the foundation for data manipulation. Strings in Python are "immutable." They can't be modified once they're created.
 

Q2: Is Python string a list?
Ans: A Python String is a sequence of characters. Using the built-in list() method, we can transform it into a list of characters. Whitespaces are treated as characters when converting a string to a list of characters. If there are leading and trailing whitespaces, they are also considered list elements.

 

Q3: What is the difference between String and list in Python?
Ans: In Python, a list is an ordered sequence of object types, whereas a string is an ordered sequence of characters. 

For example, list = ["apple", "cherry", "banana"], and string = "apple".

Key Takeaways

In this article, we learned about Strings in Python. We also learned about 

  • Accessing the characters in the string.
  • Looping in a string.
  • Calculating the length of a string.
  • Deletion/Updation in the string.
  • Formatting in the string.

 

Click here to learn about String Manipulation in Python.
 Check out this article - String slicing in Python

Want to learn Python but don't know where to start?

Start here. Coding Ninjas provide this amazing course on Python. If you are just getting into coding and want to build a strong foundation, this course is for you.

Recommended problems -

 

You can also consider our paid courses such as DSA in Python to give your career an edge over others!

 

Live masterclass