Bytes

Strings in Python

Module - 4 Data Structures in Python
Strings in Python

Overview:

The string is a collection of characters. It is one of Python's most often-used data types . Just enclosing characters in quotations 🔣 will produce it. In order to access and extract parts of strings as well as alter and modify string data , Python offers a rich collection of operators 🔢, functions, and methods for working with strings.

Strings in Python-min.png

What is a string in python?

A string in Python is a sequence of one or more characters enclosed in single or double quotes. Strings can contain letters, numbers, and symbols. They are used to store and manipulate text-based data. Strings are a fundamental data type in Python essential for working with text. They allow programmers to represent and process text in their programs. Strings can be created simply by enclosing characters in single or double quotes. For example, 'This is a string' and "This is also a string" are both strings. Various string methods are available for tasks such as replacing characters, changing cases, stripping whitespace, and searching for substrings. Once created, strings can be manipulated in many ways. Their length can be determined using the len() function, individual characters can be accessed with bracket notation, and they can be indexed and sliced to extract substrings. Strings can also be concatenated together using the + operator. Strings are a beneficial and versatile data type in Python. They facilitate text-based processing of data, which is common in natural language processing, web scraping, and many other domains. Strings, along with different data types like integers, floats , and booleans, form the fundamental building blocks of Python programs.

Creating a String in Python

string = "Hello John! Welcome!"

print(string) 

This line of code creates a string variable called "string" and assigns it the value of "Hello World!" The print() function is then used to display the value of the string to the console.

Reassigning Strings in Python

In the Python programming language, strings (sequences of characters) can have new values assigned to them using the basic assignment operator (=). Once a string has been initially defined and given a value, that string variable can later be reassigned to a new and different value.  Reassigning string variables is a fundamental part of Python and a key feature of the language that allows Python code to be concise yet versatile. Reassignment works for strings and other variable types in Python, like integers, floats, booleans, lists, dictionaries, and more.  So strings are not unique in being able to be reassigned, but Reassignment is still an important concept to understand for working with strings in Python programs. 

myString = "Hello!"

myString = "Hello! future data scientist"

print(myString)

A variable is initially set to "Hello!", then reassigned to "Hello! future data scientist" and printed.

Strings are immutable?

In programming, immutability refers to the property of an object that cannot be modified once it has been created. In the case of strings, immutability means that once a string has been created, it cannot be changed.

string1 = "Hello, World!"   
string1[0]="h"  
print(string1)             

The above example will throw an error that the str object does not support item assignment because we tried to change the string item.

How to access characters in a python string?

In Python, there are two main methods that Naveena should learn for retrieving a string's characters:

Indexing:

In Python, strings are indexed using the syntax string[index]. Indexing starts from 0 and works its way up from the left side of the string to the right side. Python also supports negative indexing where it starts from -1, where -1 represents the last character of the string.

For example:

string = "hello"

Slicing:

Slicing is another way of accessing certain parts of a string. With slicing, we can specify a start index and an end index. Slicing will return the characters between the start and end indices.

Syntax of Slicing:

slice(*start*, *end, step*)
or 
string[start🔚step]
startOptional. An integer number specifying at which position to start the slicing. Default is 0
endAn integer number specifying at which position to end the slicing
stepOptional. An integer number specifying the step of the slicing. Default is 1

For example:

string[2:5] = 'llo'
string[3:] = 'lo world!'

Using slicing, we can also access parts of the string by skipping a certain number of characters using the step we can do.

For example:

string[::2] = 'hlowrd'

How to delete a string?

You can use the built-in string method .replace() or the del keyword in Python to delete a string.

Example using .replace():

string = "Hello world"
string = string.replace("Hello", "")
print(string)

The .replace() method takes two parameters, the first is the string you want to replace, and the second is the string you want to replace it with. In this case, we are replacing "Hello" with an empty string, which deletes it.

Example using del:

string = "Hello world"
del string
print(string)

The del keyword is used to delete a variable or object. In this case, we are deleting the string variable, which deletes the entire string.

String Operators in Python

  1. Concatenation - Joins two strings together
  2. Repetition - Repeats a string a given number of times
  3. [] Slice - Accesses a specific character or range of characters in a string
  4. [: ] Range Slice - Accesses a content of characters in a string
  5. in Membership - Checks if a substring exists in a string
  6. Not in Non-Membership - Checks if a substring does not exist in a string
# Program to demonstrate string operators in Python

str1 = "Hello"
str2 = "World"

# Concatenation of two strings 
str3 = str1 + str2 
print("Concatenation of str1 and str2 is : ", str3) 

# Repetition 
str4 = str1 * 3 
print("Repetition of str1 is : ", str4) 

# Slicing 
str5 = str3[2:5] 
print("Slicing of str3 is : ", str5) 

# Range Slicing 
str6 = str3[:5] 
print("Range Slicing of str3 is : ", str6) 

# Membership 
if 'Wor' in str3: 
    print("'Wor' is present in str3") 
else: 
    print("'Wor' is not present in str3") 

# Non-Membership 
if 'x' not in str3: 
    print("'x' is not present in str3") 
else: 
    print("'x' is present in str3")
  • This program shows how to use string operators in Python.
  • The program starts by declaring two string variables, str1, and str2, with the values "Hello" and "World" respectively.
  • The program uses the + operator to combine the strings and assigns the result to a new variable, str3. This is printed.
  • The program then uses the * operator to repeat the string in str1 three times and assigns the result to a new variable, str4. This is printed.
  • Then, the program uses the [] operator to slice the string in str3 from the 2nd to the 5th character and assigns the result to a new variable, str5. This is printed.
  • The program then uses the [ : ] operator to slice the string in str3 from the beginning to the 5th character and assigns the result to a new variable, str6. This is printed.
  • Later, the program uses the in operator to check if the substring "Wor" is in the string stored in str3. If so, a message prints. If not, a different message prints.
  • Finally, the program uses the not-in operator to check if the character "x" is not in the string stored in str3. If so, a different message prints. If not, a message prints.

Conclusion:

Strings are a fundamental data type in Python and are essential for working with text-based data 📄. This lesson provides an overview of strings in Python, including what they are, how to create and reassign them 🔁, and how to access and manipulate their contents using indexing 🔢 and slicing ❄️. It also covers string operators in Python, such as concatenation 🔗, repetition 🔁, and membership testing 🔍.

Key takeaways:

  1. This lesson introduces strings in Python, including their creation, manipulation, and deletion.
  2. It also covers string operators, such as concatenation, repetition, and slicing.
  3. The lesson includes examples and explanations of accessing and modifying string data in Python.
  4. Strings are immutable objects in Python, meaning they cannot be changed once created.
  5. Strings are surrounded by either single or double quotation marks when assigned in Python.
  6. Strings can be concatenated using the '+' operator and repeated using the '*' operator.
  7. String formatting is used to insert variables into strings.
  8. Strings can be sliced or indexed to access individual characters.

Quiz:

  1. What is the output of the following code?
string1 = "Hello"
string2 = "World"
print(string1 + string2)

   a. HelloWorld

   b. Helloworld

   c. helloWorld

   d. helloworld

Answer: a. HelloWorld

  1. What is the definition of a string in Python? 
    1. A sequence of characters 
    2. A number 
    3. A function 
    4. A list

Answer: a. A sequence of characters

  1. What type of data is stored in a string?  
    1. Integer 
    2. Float 
    3. Boolean  
    4. Character

Answer: d. Character

  1. What is the syntax for declaring a string in Python? 
    1. string(str) 
    2. string str 
    3. 'str' 
    4. "str"

Answer: d. "str"

Online Python Compiler (Editor / Interpreter)
Open Compiler
Recommended Courses
Certification in Full Stack Data Science and AI
Course
20,000 people are doing this course
Become a job-ready Data Science professional in 30 weeks. Join the largest tech community in India. Pay only after you get a job above 5 LPA.
Masters Program in Data Science and Artificial Intelligence
Course
20,000 people are doing this course
Join India's best Masters program in Data Science and Artificial Intelligence. Get the best jobs in top tech companies. Accredited by ECTS and globally recognised in EU, US, Canada and 60+ countries.

AlmaBetter’s curriculum is the best curriculum available online. AlmaBetter’s program is engaging, comprehensive, and student-centered. If you are honestly interested in Data Science, you cannot ask for a better platform than AlmaBetter.

avatar
Kamya Malhotra
Statistical Analyst
Fast forward your career in tech with AlmaBetter
Explore Courses

Vikash SrivastavaCo-founder & CPTO AlmaBetter

Vikas CTO

Related Tutorials to watch

view Allview-all

Top Articles toRead

view Allview-all
AlmaBetter
Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

Š 2024 AlmaBetter