STRINGS IN PYTHON


In this tutorial we will learn about strings in python. We will learn about how to create, edit and delete strings, also we will learn about the associate operations and functions of strings.


What are Strings

Strings are one of most popular aspects of python. We can simply create a string by adding single or double quotes around characters. Now, to create your first string, all you need to do is:

string1 = ‘Hello, I am single quotes’ 
string2 = “Hello, I am double quotes”

Note: Strings are not limited to be enclosed in single or double quotes, rather you can use triple quotes as well to create a multiline string, for example:

#single quotee string1 = 'Hello, I am single quotes' print(string1) #double quotes string2 = "Hello, I am double quotes" print(string2) #triple quotes for multilines string3 = """Hey, I am triple quotes, and you are?""" print(string3)

When you will run the program, the output will be:

Hello, I am single quotes Hello, 
I am double quotes Hey, 
I am triple quotes, and you are?




How Strings are Indexed?

Like any other character in python, characters used in strings are also indexed number wise, where each character takes up a 1 byte of memory and has an address in terms of indexing. For example, if I have a string consisting of the word ‘python’ then each character of ‘python’ has a separate index and memory. Let’s say that I want to access p from the string ‘python’, then I would simply write:

string = 'python' 
print(string[0])

Since, indexing always starts from 0, so the first letter will be ‘p’ in this case which is stored at 0 index. The output of the above code will be:

p

Slicing a String

You can also slice a string by choosing the index number of characters that you want to slice through the slicing method. Let’s slice p from python by omitting index ‘0’ from the rest of the index numbers of characters:

#slicing p from python string = 'python' print(string[1:6])

Positive and Negative Indexing of Strings

We have learned that strings can be indexed positively through numbers starting from 0 onward. However, strings can be indexed negatively as well in the reverse order. For example, to view the last character of the word ‘python’ you can enter the index ‘-1’ to view letter n from ‘python’.

Positive-and-Negative-Indexing





Updating a String Through Slicing

You can update a current string with some other characters using the slicing method:

#updating a string through slicing string = 'Python Tricks' print("New String: " + string[0:6] + " Love")

Deleting a String

You can delete a string too but remember that deleting a character from a string is not possible however you can delete an entire string using del function:

#updating a string through slicing string = 'python' del string print(string) #The output will be null as we have used the del statement to delete the string

Output will be:

Traceback (most recent call last):
  File "", line 4, in 
    print(string)
NameError: name 'string' is not defined

String Operations in Python

There are many string operations that you can do with different data types and variables in Python as we have studied previously as well.





The Concatenate Operation

When you join or ‘add’ to strings together to form one new string, that process is called concatenation. The plus(+) symbol is used to concatenate or join two strings together, for example:

string1 = 'I love' 
string2 = ' Python Programming' 
adding = string1 + string2 
print(adding)

Output of concatenation will be:

I love Python Programming

Let’s do it interactively:

#Adding two strings together string1 = 'I love' string2 = ' Python Programming' adding = string1 + string2 print(adding)

You can also concatenate a string by using the * sign i.e. if you want to print a same string multiple times then you need to multiply the string with that particular number. For example:

#Adding & multiplying two strings together string1 = 'I love' string2 = ' Python Programming ' adding = string1 + string2 multiplying = string1 * 3 print(adding) print(multiplying)

Using Iteration in Strings

You can use a for loop to through the characters in your string quite easily. For example if you want to count the number of characters present in your string then you can simply:

#Counting the number of characters of a string using a for loop string = 'I love Python' count = 0 for letter in string: count = count + 1 print(count)

Testing Sub Strings within a String

You can know easily whether a sub string exists (or doesn’t exist)  within a string by using the in and not in methods. If a sub string exist within a string then the result will be in boolean form resulting True. Similarly, if a sub string doesn’t exist within a string then the boolean value will be False. For example:

#Checking whether a substring is present or not inside a string if 'p' in 'python': print(True) elif 'p' not in 'python': print(False)



Built-in Functions in Strings

Python consists of tons of built-in functions for strings. These functions/method enable strings to produce different result for a particular query. For example, if you want to play around with the text cases of your string, you can create lower(), upper(), title() and capitalize() functions to your strings. For example

string = "I love python tricks" #Creating all letters of your string to lowercase print("Lower case letters:") print(string.lower()) #Creating all letters of your string to uppercase print("Upper case letters:") print(string.upper()) #Creating first letter of each word capital print("Title case letters:") print(string.title()) #Creates first letter of your string capital print("Capital case letters:") print(string.capitalize())

There are tons of other built-in functions that you can learn here


Formatting Strings in Python

While programming, in python you may encounter syntax errors as well caused by the arrangements of characters within a string. To avoid that, we require some string formatting to encounter the relevant issues to solve errors. For example, if you use single quotes and double quotes together in a string, then that might cause an error, unless you tell python to do otherwise. For example, if you use double quotes twice along with a single quote (apostrophe) then the output will be a syntax error:

string = "He asked me, "What's your name?"" 
print(string)

Output:

string = "He asked me, "What's your name?""
SyntaxError: invalid syntax

Now, there are multiple ways to tackle the issue of this syntax error caused by using double quotes or single quotes together. You can use triple quotes around single and quotes to remove this issue or you can use escape sequence (\) to remove the issue.

#Escape single quotes print('He asked me, "What\'s your name?"') #Escaping double quotes print("He asked me, \"What's your name?\"") #Using triple quotes print('''He asked me, "What's your name?"''')




How to Ignore Escape Sequence?

So, previously we have learned about how to use escape sequence to format our strings. Now we will learn about how to use escape sequence as a character within a string by using r or R to ignore escape sequence. Let’s look at the examples:

#Using escape sequence print("This is another line: \nI am a new line") #Ignoring escape sequence print(r"This is another line: \nI am a new line")