Python: Strings
Python Strings
1 Overview
π Strings in Python
In Python, strings are used for representing textual data. A string is a sequence of characters enclosed in either single quotes (ββ) or double quotes (ββ). The Python language provides various built-in methods and functionalities to work with strings efficiently. Numbers tell computers how much or how many. Strings tell computers what β names, words, sentences, or any text. In other words, strings are how computers understand and manipulate tex
2 Strings
With strings, a computer can:
Say hello to someone.
Store a name.
Send a message.
Print a receipt.
3 Strings in Python
- Sequence of characters enclosed in single, double or triple quotes.
- Take care when mixing quotes!
- Properly mixing them:
4 Escape sequences
Include special characters in your strings by using backslash (
\)Common escape sequences:
\',\",\\,\n,\t.
World!
5 Raw strings
- Create string literals without processing escape sequences
- Add
rorRbefore the string. - Useful when working with paths, regular expressions, etc.
β>
C:.txt
β>
6 Single or double quotes?
No defined rules.
Some opinions:
Be consistent throughout your code, do not mix both types of quotes randomly, as this makes the code a bit more complex to read.
Do not use triple quotes if the string is not multi-line, as this makes the code a bit more complex to read.
7 Indexing
- Access specific string characters by index.
8 Positive indexing
- Use [index number] after the string, indicating the index to access.
- Zero-based.
l
d
9 Negative indexing
For accessing the elements of a string βbackwardsβ.
Use
-1for accessing the last element,-2for the second to last, etc.
d
e
- We get an error if we specify an index outside the range.
10 Slicing
- Extract a substring from a string.
- Specify: start index, end index and step (optional).
substring = original_string[start:end:step]
- Start is included.
- End is not included.
- Step defaults to 1 if not provided.
- Start and end default to 0 if not provided.
11 Concatenation
- With
+operator:
12 Repetition
- With
*operator:
HaHaHaHaHaHaHaHaHaHa
13 Comparison
- Standard comparison operators:
==,<,>=, etc. - Comparison performed based on the Unicode code point (ordinal) value of each character. It is similar to the way words are sorted in a dictionary.
False
True
True
14 Methods
Python provides a variety of functions, string methods, and keywords to make string manipulation easier.
Built-in functions:
len(): Function that returns the length of the string.
- String methods:
upper(): Converts the string to uppercase.lower(): Converts the string to lowercase.
find(): Returns the index of the first occurrence of a substring.
replace(): Replaces a substring with another substring.
- Trick to remove part of a string:
- Keywords:
in: Checks if a specified substring is present within a given string. It returnsTrueif the substring is found, andFalseotherwise.not in: Checks if a substring is not present in a given string.
15 Formatting
- Process of creating a new string by combining text with variables.
- Several methods:
- %-formatting.
- .format() method.
- f-strings.
15.1 %-formatting
- Old-style formatting.
- Use
%inside the string with element specifier. - Use
%after the string for adding the variables. - See specifiers at: https://docs.python.org/3/library/stdtypes.html#old-string-formatting
15.2 format() method
- New-style formatting.
- String method.
- Use curly braces
{}in text as placeholders for variables. - Specify variables as
format()arguments.
15.3 F-strings
- Most recent.
- Recommended.
- Add
fbefore the string. - Add variables inside text enclosed with curly braces
{}.
- F-strings allow nice options for formatting.
- For example, rounding to a specific number of decimals by including
:.Xf
One divided by six rounded 0
One divided by six with 1 decimal 0.2
One divided by six with 2 decimals is 0.17
- Or displaying a large integer number separating the thousands with commas to make it more readable:
Big number easy to visualize: 1,000,000
- You can find some more formatting examples here: https://www.pythonmorsels.com/string-formatting/
16 Immutability
- In Python, strings are immutable.
- Original string is never modified.
- For changing a string, we have to create a new one.
- It is forbidden to change strings using indexing:
- We should create a new string variable with the desired changes.
- For example, using slicing and concatenation:
- Another common option is to use the
replace()method:
Hello, Python!
- If the value returned by a method is not assigned to a variable, the result is lost:
17 Unicode
- Standard for representing characters from all languages.
- Python strings support Unicode by default.
- UTF-8 is the most common Unicode encoding for Python strings.
