Bytes

Strings in Python

Last Updated: 13th December, 2023

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

Loading...

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. 

Loading...

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.

Loading...

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:

Loading...
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:

Loading...

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:

Loading...

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():

Loading...

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:

Loading...

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
Loading...
  • 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?
Loading...

   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"

Module 4: Data Structures in PythonStrings in Python

Top Tutorials

Related Articles

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

Š 2024 AlmaBetter