Strings
String is a primitive data types which is surrounded by single or double quotation marks and is used to store text data or sequence of characters. When we store data in a variable and surround the data with single or double quotation marks, its data type will be string. String is an array of characters.
We can also assign string data to a variable.
Concatenation
When we have numbers in string variables, they do not sum up rather they concatenate. Concatenation is the method of joining two strings using "+" operator.
Multi-line Strings
When you write you string inside three single or double quotation marks, it becomes multi-lined string. The difference is that in simple string, all you text is printed on the same line but in multi-lined strings, line breaks are also counted.
String Length
You can also count the number of characters in your string.
Accessing Characters in a String
We know that string is a sequence of characters. So, we can access individual characters.
Note: If there is a space, it will also be given index number.
Index counting starts from zero.
This is the lengthy method for accessing individual characters. If we use loop for this purpose, it will become easy. We will discuss about loops in the coming section.
Negative Indexes
When we provide negative index, it starts from end. -1 is assigned to the last character. On the other hand, positive index starts from zero and it is from first character.
Checking in a String
We can also check if some text is present in a string or not by using "in" keyword. It gives boolean value true or false. If required text is present, it returns true otherwise false.
We can also check this by using "not in". If the required sequence of characters is present in string, it will return false otherwise true.
String Slicing
String slicing means cutting string from some given index to one less than the other given index. It returns the part of string from the given start index to one less than the given last index.
Slicing from start
When we do not provide the starting index, then by default it starts from zero index.
Slicing to end
When we do not provide the last index, then by default it ends at last index.
String Formatting
We use string formatting when we have to generate dynamic data from variables.
Index Numbers
We can use index numbers inside curly braces as placeholders for the dynamic values.
Named Indexes
Like numbered indexes, we also have named indexes. We use names inside curly braces as placeholders for the dynamic data.
String Concatenation
String concatenation is the process of joining two or more string with the help of "+" operator.
String Methods
| Name | Description | Code |
|---|---|---|
| .upper() | Converts all the lower case characters in string to upper case. | print("Hello World".upper()) |
| .lower() | Converts all the upper case characters to lower case. | print("Hello World".lower()) |
| .capitalize() | Returns first character with upper case and all other characters with lower case. | print("Hello World".capitalize()) |
| .count() | Counts the occurrences of a specified substring or element within the given string or list. | print("Hello World".count("l")) |
| .encode() | Converts a string into a sequence of bytes. | print("Hello World".encode()) |
| .center() | Center-aligns a string within a specified width. | print("Hello World".center(20, "-")) |
| .format() | Provides a way to create formatted strings | print("Hi, my name is {}".format("John")) |
| .format_map() | Formats strings by replacing placeholders with values from a mapping. | print(f"{x['name']}:{x['age']}") |
| .find() | Finds the index of the first occurrence of a specified substring within the given string. | print("Sarah".find("S")) |
| .rfind() | Finds the index of the last occurrence of a specified substring within the given string. | print("Sarah".rfind("S")) |
| .expandtabs() | Replaces tab characters ('\t') within a string with a specified number of spaces. | print(""Hello \t World".expandtabs(4)) |
| .index() | Finds the index of the first occurrence of a specified substring within the given string. | print("Hello World".index("W")) |
| .rindex() | Finds the index of the last occurrence of a specified substring within the given string. | print("Hello World".rindex("o")) |
| .join() | Concatenates elements of an iterable, such as a list or tuple, into a single string. | print(" ".join(["apple", "banana", "orange"])) |
| .replace() | Replaces a substring with a given substring. | print("Hello World".replace("Hello", "Hi")) |
| .title() | Converts a string into title case. | print("Hello World".title()) |
| .strip() | Removes starting and enging characters from a string. | print("--helloworld--".strip("-")) |
| .lstrip() | Removes starting characters from a string. | print("--helloworld--".lstrip("-")) |
| .rstrip() | Removes starting characters from a string. | print("--helloworld--".rstrip("-")) |
| .swapcase() | Creates a new string where the case of each character in the original string is swapped. | print("Hello World".swapcase()) |
| .startswith() | Checks whether a string starts with a specified substring. | print("Hello World".startswith("h")) |
| .endswith() | Checks whether a string ends with a specified substring. | print("Hello World".endswith("h")) |
| .split() | Splits a string into a list of substrings. | print("Hello World".split()) |
| .rsplit() | Splits a string into a list of substrings from right. | print("Hello World".rsplit()) |
| .splitlines() | Splits a string into a list of substrings based on line breaks. | print("hello World\nHi there".splitlines()) |
| .translate() | Perform character-level translation or deletion within a string. | print("Hello World".translate({72: 70})) |
| .maketrans() | Creates a translation table that can be used with the .translate() | print("Hello World".translate(str.maketrans("abcd", "1234"))) |
| .zfill() | Pads a numeric string with zeros (0) on the left side to achieve a specified width. | print("Hello World".zfill(16)) |
| .partition() | Splits a string into three parts based on a specified separator. | print("Hello World".partition(" ")) |
| .rpartition() | Splits a string into three parts based on a specified separator from right. | print("Hello World".rpartition(" ")) |
| .ljust() | Used to left justify a string with a specified character (or whitespace) on the right side. | print("Hello World".ljust(20, "-")) |
| .rjust() | Used to right justify a string with a specified character (or whitespace) on the right side. | print("Hello World".rjust(20, "-")) |
| .isalnum() | Checks whether all characters are alphanumeric characters in a string. | print("Hello1234".isalnum()) |
| .isalpha() | Checks whether all characters are alphabetic characters in a string. | print("Hello".isalpha()) |
| .isascii() | Checks whether all characters are ASCII characters in a string. | print("Hello".isascii()) |
| .isdecimal() | Checks whether all characters are decimal characters in a string. | print("10".isdecimal()) |
| .isdigit() | Checks whether all characters are digits characters in a string. | print("10".isdigit()) |
| .isidentifier() | Checks whether a given string is a valid identifier according to the Python language rules. | print("name".isidentifier()) |
| .islower() | Checks whether all characters are lower case characters in a string. | print("name".islower()) |
| .isnumeric() | Checks whether all characters are numeric characters in a string. | print("123".isnumeric()) |
| .isprintable() | Checks whether all characters are printable characters in a string. | print("I have a dog.".isprintable()) |
| .isspace() | Checks whether all characters are white space characters in a string. | print(" \t \n ".isspace()) |
| .istitle() | Checks whether the string follows the rules of title case. | print("ALL BOYS ARE GOOD.".istitle()) |
| .isupper() | Checks whether all the alphabetic characters are upper case characters in a string. | print("ALL BOYS ARE GOOD.".isupper()) |
| .casefold() | Converts the string into lower case. | print("ALL BOYS ARE GOOD.".casefold()) |
Practice Exercises
Complete these exercises to reinforce your learning and earn XP