
String operators in Python are different types of operators that can be applied to strings. You can see in the output that we got NameError which means that our variable my_str doesn’t exist: String Operators in Python However, we can delete the string itself: my_str = "hello" Now let us try to replace the whole string with another: Advertisements my_str = "hello"ĭeleting certain elements using indexes is not supported as well: my_str = "hello" Let’s try to change the character in the string: my_str = "hello"Īs we can see in the output it causes a TypeError: However, we can delete the entire string using del or create a new string with the same name to replace it completely. In Python, we cannot update or delete string elements like in lists since strings are immutable, and trying to do so will cause an error. Hel How to Modify or Change a String in Python? Slicing characters between 5th and 2nd last character: Print("\nSlicing characters between 5th and 2nd last character: ") # printing characters between 5th and 2nd last character Slicing in a string is done with the slicing operator (colon). We can access a range of characters in a string using the slicing method. # trying to get character using float index # trying to get character using index out of range Print('my_str =', my_str) # using index 4Īttempting to access a character outside the index range will raise an Inde圎rror, and trying to enter a non-integer number as an index or any data type other than an integer will result in a TypeError. Print('my_str =', my_str) # using negative index -1 Print('my_str =', my_str) # using negative index -5 Print('my_str =', my_str) # using index 0 Advertisements # accessing string characters in Python However, we can also use negative indexing to access characters from the end of the string.įor example, -1 refers to the last character, -2 refers to the pre-last character, and so on. In Python, we can access individual elements of a string using the indexing method, and the index always starts at 0. If we run this code, we see that the output and the data type are the same, no matter what quotes we used: Advertisements Ĭool How to Access Characters in Python Strings?

# strings with triple quotes can be multi-line string # using function type() to get the data type of my_string, Triple quotes in Python are used to represent multi-line strings and docstrings. We must enclose characters in single quotes, double quotes, or even triple quotes to create strings. What Are Python Strings?Ī string in Python is an object containing sequences of character data. We will learn how to access some elements of strings and call various methods to manipulate, format, and modify strings using Python. Python provides a rich set of built-in operators, functions, and methods for working with strings. This tutorial will focus on the Python string data type.


