Python Strings

Strings are a sequence of characters enclosed in quotes (either single or double). In Python, strings are considered as a built-in data type, and they are immutable, which means that once a string is created, it cannot be modified.

Creating Strings

Creating a string in Python is as simple as assigning a value to a variable using quotes. Quotes can be single, double and even triple quotes. For example:

my_string = "hello"
my_string = 'hello'
my_string = '''hello
               this is test
               now it ends here'''

String Indexing:

String indexing refers to the process of accessing individual characters in a string by their position. In Python, each character in a string is assigned a numerical index starting from 0 for the first character, and increasing by 1 for each subsequent character.

To access a character at a specific index, you can use the square bracket notation [] along with the index value. For example, if you have a string my_string = “Hello, World!”, you can access the first character (H) using the index 0 as follows:

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

#output: H

You can also use negative indexing to access characters from the end of the string. In this case, the last character in the string has an index of -1, and the index values decrease by 1 for each previous character. For example, to access the last character in the string (the exclamation mark), you can use the index -1 as follows:

my_string = "Hello, World!"
print(my_string[-1])

#Output: !

my_string = "hello"
print(my_string[0]) # Output: h
print(my_string[1]) # Output: e
print(my_string[2]) # Output: l
print(my_string[3]) # Output: l
print(my_string[4]) # Output: o

String Slicing:

String slicing is a way of accessing a portion of a string by extracting a substring. Slicing works by specifying a range of indexes separated by a colon inside the square brackets. The syntax for slicing a string in Python is as follows:

string[start_index:end_index:step_size]

where:

  • start_index is the index where the slice starts (inclusive).
  • end_index is the index where the slice ends (exclusive).
  • step_size is the number of characters to skip between each character in the slice (optional).

If start_index is not specified, the slice starts at the beginning of the string (index 0). If end_index is not specified, the slice goes all the way to the end of the string. If step_size is not specified, it defaults to 1. Here are some examples of using slicing to extract substrings from strings:

# Get the first three characters of a string
my_string = "Hello, World!"
print(my_string[0:3])   
# Output: Hel

# Get the last four characters of a string
my_string = "Hello, World!"
print(my_string[-4:])   
# Output: ld!

# Get every other character of a string
my_string = "Hello, World!"
print(my_string[::2])   
# Output: Hlo ol!

# Get a substring starting at index 2 and going up to but not including index 7
my_string = "Hello, World!"
print(my_string[2:7])   
# Output: llo, 

# Get a substring starting at index 2 and going up to but not including index 7, with a step size of 2
my_string = "Hello, World!"
print(my_string[2:7:2])   
# Output: lo

You can also use negative indexing with slicing to count indexes from the end of the string:

# Get the last three characters of a string
my_string = "Hello, World!"
print(my_string[-3:])   
# Output: ld!

# Get a substring starting at index -7 and going up to but not including index -2
my_string = "Hello, World!"
print(my_string[-7:-2])   
# Output: World

String Concatenation

Python string concatenation refers to the process of combining two or more strings into a single string. In Python, you can concatenate strings using the + operator or the += operator. Here’s an example of using the + operator to concatenate two strings:

first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)   

# Output: John Doe

In this example, the + operator combines the first_name and last_name strings with a space in between, resulting in the full_name string. You can also use the += operator to concatenate strings:

greeting = "Hello, "
name = "John"
greeting += name
print(greeting)   
# Output: Hello, John

In this example, the += operator appends the name string to the end of the greeting string, resulting in the concatenated string "Hello, John".

It’s worth noting that you can also use the * operator to repeat a string a certain number of times. For example:

string = "abc"
print(string * 3)   
# Output: abcabcabc

In this example, the * operator repeats the string three times, resulting in the concatenated string "abcabcabc".

Python also provides several string methods that can be used for concatenation, such as join(). The join() method takes an iterable of strings and joins them together with the calling string as a separator. Here’s an example:

words = ["Hello", "world", "!"]
separator = " "
message = separator.join(words)
print(message)   
# Output: Hello world !

In this example, the join() method joins the strings in the words list with a space separator, resulting in the concatenated string "Hello world !".

String Repetition

In Python, you can repeat a string a certain number of times using the * operator. The syntax for string repetition is as follows:

string * n

where string is the string to be repeated and n is the number of times to repeat the string. Here’s an example of using the * operator to repeat a string:

string = "Hello"
repeated_string = string * 3
print(repeated_string)   
# Output: HelloHelloHello

In this example, the * operator repeats the string "Hello" three times, resulting in the string "HelloHelloHello".

It’s important to note that the * operator only works when the first operand is a string and the second operand is an integer. If you try to repeat a non-string object or repeat a string with a non-integer value, Python will raise a TypeError.

string = "Hello"
repeated_string = string * "3"   
# Raises TypeError

n = 3
repeated_string = 3 * n   
# Raises TypeError

String Updation

In Python, strings are immutable, which means that once a string object is created, it cannot be modified in place. However, you can create a new string by deleting or updating parts of the original string. To delete a character or a substring from a string, you can use slicing with the + operator. Here’s an example:

string = "Hello, world!"
new_string = string[:7] + string[8:]
print(new_string)   
# Output: Hello world!

In this example, the new_string variable is created by concatenating the substring "Hello, " (which includes the comma) and the substring "world!" (which excludes the comma) from the original string.

To update a character or a substring in a string, you can also use slicing with the + operator. Here’s an example:

string = "Hello, world!"
new_string = string[:5] + "Python" + string[12:]
print(new_string)   

# Output: HelloPython!

In this example, the new_string variable is created by concatenating the substring "Hello" (which excludes the comma) with the string "Python" and the substring "!" from the original string.

It’s worth noting that you can also use the replace() method to update a substring in a string. The replace() method takes two arguments: the substring to be replaced and the replacement substring. Here’s an example:

string = "Hello, world!"
new_string = string.replace("world", "Python")
print(new_string)   # Output: Hello, Python!

In this example, the new_string variable is created by replacing the substring "world" with the string "Python" in the original string.

In summary, while you can’t modify a string directly, you can create a new string by deleting or updating parts of the original string using slicing and concatenation, or by using the replace() method.

String Deletion

To delete an entire string in Python, you can use the del keyword followed by the name of the string variable. Here’s an example:

string = "Hello, world!"
del string

In this example, the del keyword deletes the string object referred to by the string variable, effectively removing the string from memory. It’s worth noting that once you delete a string using del, you cannot access it again. If you try to reference the deleted string variable, Python will raise a NameError. Here’s an example:

string = "Hello, world!"
del string
print(string)   
# Raises NameError: name 'string' is not defined

In general, you should be careful when using del to delete objects in Python, as it can lead to unexpected behavior and memory leaks if used improperly.

String Formatting

You can format a string in Python using placeholders. Placeholders are specified using curly braces {}. For example:

name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
# Output: My name is Alice and I am 25 years old.

More detailed information about string formatting can be read from a separate article which is linked here.

In Summary, learning about strings in Python is essential for any programmer who wants to work with text data in their programs. Strings are used to store and manipulate textual information, such as names, addresses, and messages. Understanding the various operations that can be performed on strings, such as indexing, slicing, concatenation, and repetition, can make it easier to work with text data and to build more complex programs that process text in various ways. Additionally, learning about the immutability of strings and how to create new strings from existing ones can help improve the performance of your programs and avoid unexpected behavior. Overall, gaining a solid understanding of strings in Python can make you a more effective and efficient programmer.

The codes (if any) mentioned in this post can be downloaded from github.com. Share the post with someone you think can benefit from the information

Leave a Comment

Share this