How to use string in python
What is String in Python?A string is a sequence of characters. Show
A character is simply a symbol. For example, the English language has 26 characters. Computers do not deal with characters, they deal with numbers (binary). Even though you may see characters on your screen, internally it is stored and manipulated as a combination of 0s and 1s. This conversion of character to a number is called encoding, and the reverse process is decoding. ASCII and Unicode are some of the popular encodings used. In Python, a string is a sequence of Unicode characters. Unicode was introduced to include every character in all languages and bring uniformity in encoding. You can learn about Unicode from Python Unicode. How to create a string in Python?Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple quotes can be used in Python but generally used to represent multiline strings and docstrings.
When you run the program, the output will be: Hello Hello Hello Hello, welcome to the world of Python How to access characters in a string?We can access individual characters using indexing and a range of characters using slicing. Index starts from 0. Trying to access a character out of index range will raise an Python allows negative indexing for its sequences. The index of
When we run the above program, we get the following output: str = programiz str[0] = p str[-1] = z str[1:5] = rogr str[5:-2] = am If we try to access an index out of the range or use numbers other than an integer, we will get errors.
Slicing can be best visualized by considering the index to be between the elements as shown below. If we want to access a range, we need the index that will slice the portion from the string. String Slicing in PythonHow to change or delete a string?Strings are immutable. This means that elements of a string cannot be changed once they have been assigned. We can simply reassign different strings to the same name.
We cannot delete or remove characters from a string. But deleting the string entirely is possible using the
Python String OperationsThere are many operations that can be performed with strings which makes it one of the most used data types in Python. To learn more about the data types available in Python visit: Python Data Types Concatenation of Two or More StringsJoining of two or more strings into a single one is called concatenation. The + operator does this in Python. Simply writing two string literals together also concatenates them. The * operator can be used to repeat the string for a given number of times.
When we run the above program, we get the following output: str1 + str2 = HelloWorld! str1 * 3 = HelloHelloHello Writing two string literals together also concatenates them like + operator. If we want to concatenate strings in different lines, we can use parentheses.
Iterating Through a stringWe can iterate through a string using a for loop. Here is an example to count the number of 'l's in a string.
When we run the above program, we get the following output: 3 letters found String Membership TestWe can test if a substring exists within a string or not, using the keyword
Built-in functions to Work with PythonVarious built-in functions that work with sequence work with strings as well. Some of the commonly used ones are Similarly,
When we run the above program, we get the following output: list(enumerate(str) = [(0, 'c'), (1, 'o'), (2, 'l'), (3, 'd')] len(str) = 4 Python String FormattingEscape SequenceIf we want to print a text like He said, "What's there?", we can neither use single quotes
nor double quotes. This will result in a
One way to get around this problem is to use triple quotes. Alternatively, we can use escape sequences. An escape sequence starts with a backslash and is interpreted differently. If we use a single quote to represent a string, all the single quotes inside the string must be escaped. Similar is the case with double quotes. Here is how it can be done to represent the above text.
When we run the above program, we get the following output: He said, "What's there?" He said, "What's there?" He said, "What's there?" Here is a list of all the escape sequences supported by Python.
Here are some examples
Raw String to ignore escape sequenceSometimes we may wish to ignore the escape sequences inside a string. To do this we can place
The format() Method for Formatting StringsThe We can use positional arguments or keyword arguments to specify the order.
When we run the above program, we get the following output: --- Default Order --- John, Bill and Sean --- Positional Order --- Bill, John and Sean --- Keyword Order --- Sean, Bill and John The We can also format integers as binary, hexadecimal, etc. and floats can be rounded or displayed in the exponent format. There are tons of formatting you can use. Visit here for all the string formatting available with the
Old style formattingWe can even format strings like the
old
Common Python String MethodsThere are numerous methods available with the string object. The
How do you write a string in Python?To create a string, put the sequence of characters inside either single quotes, double quotes, or triple quotes and then assign it to a variable. You can look into how variables work in Python in the Python variables tutorial. For example, you can assign a character 'a' to a variable single_quote_character .
How does strings work in Python?Python strings are "immutable" which means they cannot be changed after they are created (Java strings also use this immutable style). Since strings can't be changed, we construct *new* strings as we go to represent computed values.
How do you access a string in Python?String Indexing
Individual characters in a string can be accessed by specifying the string name followed by a number in square brackets ( [] ). String indexing in Python is zero-based: the first character in the string has index 0 , the next has index 1 , and so on.
What does [Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.
|