04. Python Strings
Python Strings Learning Outcome¶
Creating Strings: In Python, you have the option to create strings by enclosing text with either single quotes ('') or double quotes ("").
Accessing Characters: Indexing or slicing allows you to obtain specific characters within a string.
String Concatenation: You have the option of combining strings either by utilizing the + operator or through the implementation of the += operator.
String Methods: Python offers an extensive array of pre-installed string methods that can be utilized to handle strings, such as upper(), lower(), strip(), replace(), and numerous others.
String Formatting: Python offers several approaches for string formatting, such as utilizing the format() technique and f-strings.
Escape Sequences: Special characters known as escape sequences enable the representation of characters in a string that would otherwise be challenging to express, such as quotes, newlines, and tabs.
String Operations: Python offers a variety of operators that can be utilized to conduct actions on strings, including but not limited to comparison operators, membership operators, and logical operators.
Use escape characters for special characters such as quotation marks.
Create powerful and efficient programs using strings.
Format text, create patterns, and even encrypt data with strings.
Advantages of Python Strings¶
"Strings" are utilized extensively across various domains, serving purposes like preserving and modifying textual information, indicating identities, locations, and other types of data that can be conveyed as text.
Python offers an extensive range of string methods that facilitate the manipulation and handling of strings in diverse ways. These methods simplify the execution of routine tasks, such as changing strings to uppercase or lowercase, substituting substrings, and segmenting strings into lists.
Strings are immutable meaning they cannot be altered once they are created, providing reassurance that the value of a string will not change unexpectedly. This characteristic can prove advantageous in specific scenarios since it ensures that the string's value remains constant and predictable.
Python includes built in support for strings, eliminating the need to import external libraries or modules to manipulate them. This simplifies working with strings and streamlines your code's complexity, making it simpler to begin working with strings.
Python offers a succinct syntax for generating and manipulating strings, rendering it effortless to compose and comprehend code that handles strings.
Disadvantages of Python Strings¶
When working with substantial amounts of text data, strings may not be the most efficient option. If, for example, you need to execute numerous string operations, like substituting substrings or dividing the string into several substrings, it can be sluggish and require significant resources.
Representing complex data structures like lists or dictionaries using strings can pose a challenge. In such situations, it would be more effective to use an alternative data type, like a list or a dictionary, to accurately capture the data.
Application of Python Strings¶
Web development: Python is a popular language for web development, and developers use Python strings to dynamically create HTML, CSS, and JavaScript code.
Data analysis: In data analysis, strings are frequently used to store text-based data like customer feedback, social media posts, or product descriptions. Python strings are useful for data cleaning, normalization, and processing to extract insights.
Natural Language Processing (NLP): NLP is a subfield of AI that involves processing and analyzing human language. Python strings are crucial in NLP, where they are used to store and manipulate text data, including text classification, sentiment analysis, and named entity recognition.
Automation: Python strings are widely used in automation tasks to process and manipulate file paths, automate email sending, and generate reports.
Scientific computing: In scientific computing, strings are used to store and process data related to scientific research. For instance, scientists may use Python strings to store DNA sequences, chemical structures, or astronomical data.
What is a String?¶
- In Python A string is a sequence of characters. No more, no less.
- In Python, anything inside quotation marks is referred to as a "string".
- You can use either single or double quotes.
- Using double quotes has the advantage of allowing a single quote character to be included in the string.
- Strings may also be created from other objects using the str constructor.
#Double Quotes
#Code Example
middle_name = 'Mary'
type(middle_name)
str
#Code Example
last_name = " Oaks"
last_name
' Oaks'
type(last_name)
str
#String Operators¶
The + operator¶
- The
+operator combines two strings into one(Concatenates)
#Code Example
'Mary Oaks'
'Mary Oaks'
- If several string literals are placed together, they will be combined into a single string.
#Code Example
school_name = 'The' ' Data' ' Armory' ' Academy'
school_name
'The Data Armory Academy'
- This feature is especially helpful when needing to divide long strings.
- NB: Put strings within parentheses.
#Code Example
country_names =('Kenya' 'Uganda' 'Tanzania')
print(country_names)
KenyaUgandaTanzania
- It is not possible to concatenate a variable and a string literal.
#Code Example
- Use the + operator to concatenate variables or a variable and a literal.
#Code Example
first_name = 'Kelly'
middle_name = 'Rowland'
students_name = first_name + ' ' + middle_name
students_name
'Kelly Rowland'
students_name = first_name middle_name
File "C:\Users\USER\AppData\Local\Temp/ipykernel_3272/3084417407.py", line 1 students_name = first_name middle_name ^ SyntaxError: invalid syntax
new_student = first_name + ' ' + 'Bill'
new_student
'Kelly Bill'
The *operator¶
- In Python, the
*operator can be used to create multiple copies of a string. Here are some examples:
#Code Example
String indexing¶
The bracket
[]operator allows us to access individual characters in a string.It takes an index as an argument and returns the character at that position in the string.
For example,lets get the first letter of the string
name.
#Code Example
- Python strings are indexed from left to right, with the first character at index 0, the second at index 1, and so on.
- You can access a specific character in a string using indexing, such as
my_string[0]to get the first character.
#Code Example
- We can also use negative indices to access characters from the end of the string.
#Code Example
string[:i] + string [i:]will be equal to string
- Negative indices begin with -1, and
-0is equivalent to0.
#Code Example
#Code Example
Escape Characters¶
- To use both single and double quotes in a string, you must use escape characters.
- An escape character enables you to use characters that would otherwise be impossible to include in a string.
- An escape character is a backslash \ followed by the desired character to be included in the string. This allows for special characters, such as quotation marks, to be used without disrupting the string.
''' \' To add a Single quote
car = 'This is Mr. Ken\'s car'
\" To add Double quote
her_husband = "He is a \"good\" man"
\t To add Tab
welcome_message = 'How did you know\tAbout the data Armory\tMake sure you share and subscribe'
\n To add a Newline (line break)
welcome_message = 'How did you know\nAbout the data Armory\nMake sure you share and subscribe'
\\ To use Backslash
back_slash = ' An escape character is a backslash \\' '''
#Code Example
- Without the use of print(), a new line character (\n) will be included in the output.
#Code Example
- A backslash can be placed at the end of a line to ignore the newline character.
- A backslash \ indicates that the current line should be continued on the next line.
- It is used to break up a long line of code into smaller sections for readability.
#Code example
Raw Strings¶
- A raw string ignores all escape characters and prints any backslash it contains. No special treatment is given to the backslash.
#Code Example
- There is an important consideration when using raw strings, which is that it cannot end with an uneven number of \ characters.
#Code Example
- How to end a raw string with an odd number of backslashes.
#Use regular strings and double the backslashes:
#len function
- The len() function can be used to determine the number of characters in a string. In this case, using the len() function on the string
namewould return the value12.
#Code Example
#Stripping Whitespace
- The
rstrip()method can be used to remove any extra whitespace from the right end of a string. For example:
#Code Example
Multiline String¶
- String literals can span multiple lines and are delimited by either three single quotes or three double quotes. For example, to create a multiline string in Python we can write:
#Code Example
#String slices
Python allows for string slicing, which means accessing a specific portion of a string.
Like lists, strings in Python can be accessed using indexes and slices. The syntax for slicing a string is the same as slicing a list, with the start and end indices separated by a colon. For example,
string[0]would return the first character of the string, whilestring[0:3]would return the first three characters. The syntax is as follows:Because Python (like many programming languages) uses zero-based indexing
#Code Example
#Code Example
- In Python you can capture a slice from one string variable and store it in a separate string variable using slicing notation.
- For example, to capture the first three characters of the string variable
nameand store it in a separate variablefirst_three, you can use the following code:
#Code Example
Points to Note:
- Negative indexing and slicing: You can also index and slice strings from right to left using negative indices. For example,
my_string[-1]would give you the last character, andmy_string[-4:-1]would give you a substring starting from the fourth character from the end and ending at the second-to-last. - Slice step: You can also specify a step size in the slice, which allows you to skip characters in the string. For example,
my_string[0:6:2]would give you every other character from the first to the fifth character. - Immutable strings: It's important to remember that strings in Python are immutable, which means you cannot modify them directly. However, you can create new strings by concatenating or slicing existing strings.
#Code Example
- Using negative numbers can be useful when working with strings of unknown length or when you want to access characters starting from the end of the string.
#Code Example
- You can reverse a string using slicing by specifying a step of -1. For example:
#Code Example
- You can also use indexing to combine strings.
#Code Example
#The in and not in Operators
- The
inandnot inoperators in Python can be used to check if a substring is present or absent, respectively, in a given string. - The operator returns a boolean value (
TrueorFalse) based on whether the substring is found in the string or not.
#Simple Looping and counting program;
# using the in operator
# using the not in operator
- These operators can be useful for various string operations, such as searching for a specific substring or checking if a password meets certain requirements.
- These membership operators can be used with a wide range of Python objects that support membership testing, such as lists, tuples, sets, dictionaries, and strings.
#Password
#String Comparison
- To check if two strings are equal, you can use the
==operator. For example:
#Code Example
- To check if two strings are not equal, you can use the
!=operator. For example,if my_string1 != my_string2:will evaluate toTrueifmy_string1is not equal tomy_string2.
#Code Example
- String comparison: You can also compare two strings to determine which one is greater or lesser than the other, based on their ASCII values. For example,
if my_string1 < my_string2:will evaluate toTrueifmy_string1comes beforemy_string2in alphabetical order.
#Code Example
Case sensitivity: By default, string comparison in Python is case-sensitive, which means that "apple" and "Apple" are considered different strings.
If you want to perform a case-insensitive comparison, you can convert the strings to lowercase or uppercase using the
lower()orupper()method before comparing them.By mastering these techniques for comparing strings in Python, you can effectively perform conditional checks and string operations in your code.
String Methods¶
Several string methods can be used to analyze strings or create transformed string values. This section describes the methods that you will use most frequently.
Here are some examples of Python string methods:
#Code Example
- For more information on these and other string methods in Python, see the official Python documentation.
#Strings are immutable
- In Python, strings are immutable. This means that once a string is created, it cannot be modified.
- Any operation that appears to modify a string actually creates a new string. Here are some examples:
#Code Example
- Some string methods that have names beginning with the word "is" include:
#Code Example
#Strings are immutable
- In Python, strings are immutable. This means that once a string is created, it cannot be modified. Any operation that appears to modify a string actually creates a new string. Here are some examples:
#The dir() on strings
- The
dir()function in Python returns a list of all the available attributes and methods of an object. Here are some code examples usingdir()on strings:
#Code Example
- The output of dir() on a string object will also include a number of string attributes, such as class, doc, and len(). These attributes can be used to obtain information about the string object, such as its class, documentation, or length.
- You can use the built-in help() function. Simply pass the attribute or method as an argument to help(), and it will display the documentation and usage information for that attribute or method.
#Code Example
String Formatting¶
The % operator(Old Way)
- The % operator in Python is used to format strings by replacing placeholders with the values of variables.
#Code Example
#Code Example