Pull the Right Strings: Level Up Your Python Game


Still thinking about the response that you haven’t received from your favourite person?, Trying to think of a catchy caption for Instagram, or Googling something random at 2 a.m. Texts have become an integral part of our everyday lives. We deal with them all the time so much so that we don’t even exclusively pay attention on them anymore. In the digital world, this everyday interaction boils down to something much simpler, i.e., characters strung together to form meaning.
What are Strings in Python?
In the programming world, this concept lives on as a string, a sequence of characters, whether letters, numbers, symbols, or spaces, typically enclosed in quotation marks. It is a fundamental data type used to represent textual information and drive countless features in the software we use every day!
In Python, Strings are a collection of characters written between quotes. They are immutable, meaning their value cannot be changed after creation. Strings can be enclosed in single quotes ('...'
), double quotes ("..."
), or triple quotes ("""..."""
or '''...'''
). Triple quotes are used for multiline strings.
str = "Hello, I am a string"
So, can we say that Strings are arrays of character type? Yes, but no. Strings and arrays in Python are two different data types, and the main reason for this is that Strings are immutable, whereas Arrays are mutable.
How to declare String variables and assign values to them?
Strings are declared just like any other data type variable in Python.
# Some of the ways to declare and assign string variables in Python
str1 = 'Python'
str2 = "Hello, world!"
str3 = ''' Welcome
to a new world of
possibilities '''
a, b, c = "a", "2", "z" #Note that '2' in b is string values, not a integer
How to access characters in Strings?
Strings in Python are sequences of characters, so we can access individual characters using indexing, with the first character at index 0. Negative indexing is also supported, where -1 refers to the last character. Let’s have a look at the diagram below for better understanding.
# accessing 'e' in string variable str2 using index value
str[1]
str[-12]
#fetch 'e' from str2 and display it
character = str[1] # or we could have use negative index i.e. str[-12]
print(character)
Note: Accessing an index out of range will cause an IndexError. Only integers are allowed as indices and using a float or other types will result in a TypeError.
String slicing in Python
String slicing is a way to extract a portion of a string by specifying the start and end indexes. The syntax for slicing is string[start:end:step_size], where start is the starting index and end is the stopping index, which is always excluded, and step_size indicates the number of steps that need to be taken to move from one index to another.
The default values for start, end, and step_size are 0, n/-1, 1, respectively.
“Strings in Python are immutable.”
The term immutable means things cannot be changed after they are created. It is necessary to be extremely cautious while working with Python because of its immutable nature. If we need to manipulate strings, then we can use methods like concatenation, slicing, or formatting to create new strings based on the original.
… but why are strings immutable? They were designed that way by their creator, and as end users, we are not in a position to alter their nature. Let’s understand this behaviour of string through examples
#creating a string
str2 = "Hello, world!"
str[2] = 'L' # this statement will produce an error because strings are immutable
below image shows the exact error that will appear on the console.
Built-in String functions in Python
Python provides various built-in methods to manipulate strings. Below are some of the most useful methods.
Function name | Syntax | Description | Example |
len() | len(string_name) | len() returns the total number of characters in a string | len(str2) |
upper() | string_name.upper() | upper() method converts all characters to uppercase. | str2.upper() |
lower() | string_name.lower() | lower() method converts all characters to lowercase. | str2.lower() |
split() | string_name.split(separator, maxsplit) | split() splits the string at the specified separator, and returns a list | str2.split(“ ”) |
index() | string_name.index(elmnt, start, end) | index() searches the string for a specified value and returns the position of where it was found | str2.index(“Hello“) |
strip() | string_name.strip(separation_character) | strip() removes leading and trailing whitespace from the string | str2.strip(“,“) |
replace() | string_name.replace(current_string, new_string) | replace() replaces all occurrences of a specified substring with another. | str2.replace(“Hello”, “hello”) |
find() | string_name.find() | find() returns the index of the first occurrence of a specified substring. If the substring is not found, it returns -1. | str.find(“world“) |
count() | string_name.count(value, [start, end]) | count() method returns the number of times a specified value appears in the string. | str2.count(“Hello“) |
isupper() | string_name.isupper() | is upper() returns True if all characters in the string are upper case | str2.isupper() |
islower() | string_name.islower() | islower() returns True if all characters in the string are lower case | str2.islower() |
isalpha() | string_name.isalpha() | isaplha() returns True if all characters in the string are in the alphabet | str2.isalpha() |
isdigit() | string_name.isdigit() | isdigit() returns True if all characters in the string are digits | str2.isdigit() |
swapcase() | string_name.swapcase() | swapcase() swaps cases, lower case becomes upper case and vice versa | str2.swapcase() |
and many more.
Bouns
Strings are undoubtedly Python’s most fascinating data structure, and I don’t think we need more reasons to justify that, do we? Umm, let’s take a look at one more feature that Python’s strings provide us. Strings in Python allow us to use not just arithmetic operators but also comparison operators, helping us make our jobs easier.
Let’s look at the image below to understand it in the best way possible.
In the above and below examples, each string character’s ASCII value is being compared, and that is how the results are evaluated
Do I need to mug up all the ASCII values? The answer would be no because in Python has made our jobs easier, yet again. Function ord(character) is a single-character input type function that helps us fetch the ASCII value of their corresponding character, just like we saw in the above written snippet.
ord('a') #97
ord('Z') #90
"Zebra" > "apple" #False
"cat" < "catalog" #True
Conclusion
In Python, strings are versatile and easy to work with, making text manipulation straightforward for not just beginners but also for pros. From slicing and using string methods to handling user input, Python provides powerful tools for handling strings efficiently. Understanding these basics is essential for tasks like data processing, user input handling, and more. As you explore further, strings will become one of your most relied-upon tools in Python programming.
Thanks a ton for taking the time to read through—it means a lot!
Special mentions: Hitesh Choudhary , #PriyaBhatia, #chaicode #geeksforgeeks #W3Schools
Previous article
Subscribe to my newsletter
Read articles from Sonali Shiromani directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
