Scripts in Python
In the world of programming, we say text"String"Whether it consists of a single letter, a word, a sentence or a very large text.
From this point of view, we conclude that the text is a series of characters that do not have a specific size.
In Python a class or type is created strspecifically for storing text values.
Technical information about scripts in Python
The type strdepends on the encodingUnicodeThis means that you will not face any problem when dealing with Arabic, English, French texts, etc.
Script variables in Python(which kind str)considered asImmutable. This means that when you define any variable in which you store text, this text will reserve a place in memory for it, whatever its size. And if you give a new value to this variable, it will delete the old value from memory and create a new place in memory and put the new value in it because the same value cannot be modified in the same place in memory.
method of definitionstr in python
To define a text in Python we use a symbol ', a symbol ", or a symbol """.
Is there a difference between these symbols?
As for the symbol 'and the symbol ", there is no difference between them. Either one can be used to define one-line text.
As for the symbol '''and the symbol """, there is no difference between them. Either one can be used to define a large text consisting of several lines.
In the following example, we have defined three variables containing text values. We notice that we have defined each variable with a different symbol.
Example 1: Defining variables with text values in Python
# Here we have defined three variables containing text values
name = 'Mahamad'
job = "Programmer"
message = '''This string that will span across multiple lines. No need to use newline characters for the next lines.
The end of lines within this string is counted as a newline when printed.'''
# Here we display the values of the text variables in an ordered manner
print('Name: ', name)
print('Job: ', job)
print('Message: ', message)
• We will get the following result when running.
Job: Programmer
Message: This string that will span across multiple lines. No need to use newline characters for the next lines.
The end of lines within this string is counted as a newline when printed.
In the following example, we have defined a text that contains the same symbols that are used to identify texts.
second example
# Contains a text value Here we have defined a variable named text = """In this line we print 'single quotations' In this line we print "double quotations" """ # text Here we have shown the value of the variable print(text)
• We will get the following result when running.
In this line we print "double quotations"
Merging scripts in Python and the concept ofConcatenation
ConcatenationIt means placing a series of texts next to each other to display as one text. And this is what you will need in any application.
For example, in the programs or websites that you use, you notice that when you create a new account, you are asked to enter your name in two stages as follows:
- Name(First Name).
- family name(Last Name).
After you create your account, you will notice that it has displayed your full name(Name + family name).
When you put the two names next to each other as if they were one text, the programmer actually only combined them and not retyped them again.
In the following example, we will define the variable first_nameto put the name in it, the variable last_nameto put the last name in it, and the variable full_nameto put the name and last name in it.
Example of text merging in Python
# And we put a text in it that represents the name first_name here we created the variable first_name = 'saddam' # And we put a text in it that represents the last_name. Here we created the variable last_name = 'alawiri' # And we added between them an empty space last_name and the last name in the variable first_name and put the name in the variable full_name here we created the variable full_name = first_name + ' ' + last_name # Next, the full name that we have merged and put in it will be displayed full_name. Here we have shown the value of the variable print(full_name)
• We will get the following result when running.
How to combine texts in Python
You can apply theConcatenationIn Python in two ways:
using the agent
+.Or by using a function
join()that gives you more advanced ways to combine texts. You will find a detailed explanation of this function later in this lesson.
Automating text in Python
If you put two text values next to each other and put a blank space between them(or multiple blank spaces)The Python interpreter will integrate them for you automatically.
An example of automatically merging texts in Python
s = 'saddam' ' alawiri ' # s Here we put two text values next to each other and store them in the variable print(s) # Let's make sure the two scripts are combined correctly s3 Here we've shown the value of the variable
• We will get the following result when running.
Accessing text characters in Python
Suppose we define a variable whose name sand value are text'welcome to harmash.com'
Example
s = 'welcome to harmash.com'
The text of the variable will be stored sin memory, letter by letter, in the order as shown in the following figure.
How to access text characters in Python
If you want to access the characters of this text, you have two options:
Accessing text characters from left to right. This happens automatically when you use numbers greater than or equal to 0 to access these characters.
Accessing text characters from right to left. This happens automatically when you use numbers less than 0 to access these characters.
Accessing text characters from left to right in Python
In the event that you want to pass through the characters of this text from left to right, the cells will be considered to have been numbered starting from 0 as follows.
Information: The method of numbering the digits is called(Forward Indexing).
In the following example, we will print the content of the first 7 digits, starting from the left side, and thus we will get the word welcome.
An example showing how to access text characters from left to right
# contains text s Here we have defined a variable named s = 'welcome to alawirisaddam.com' # And we started from the left s here we printed the first 7 characters in the variable print(s[0] + s[1] + s[2] + s[3] + s[4] + s[5] + s[6])
• We will get the following result when running.
Accessing text characters from right to left
In the event that you want to pass over the characters of this text from right to left, the cells will be considered to have been numbered starting from the number 1- as follows.
Information: The method of numbering the digits is called(Backward Indexing).
In the following example, we will print the content of the last 3 digits, starting from the right side, and thus we will get the word com.
An example showing how to access text characters from right to left
# contains text s Here we have defined a variable named s = 'welcome to alawirisaddam.com' # And we started from the right s here we printed the last 3 characters in the variable print(s[-3] + s[-2] + s[-1])
• We will get the following result when running.
Finding the number of text characters using the functionlen(s)
To find out the number of characters of any text we call the function len()and then pass the text to it in place of the parameter s.
Note: Blank spaces(White Spaces)It is also calculated.
An example illustrates this
s = 'welcome to alawiri.com' # s Here we have defined a text variable named
print('Length of s =', len(s)) # len() that the s function will return Here we have printed the number of characters(s) of the variable
• We will get the following result when running.
technical terms
The number of text characters is calledLength.
The cell number is called .Index.
The digits are calledIndices.
If we take part of the text. The part that is taken is calledSubstring.
You, as a programmer, can take advantage of the cell numbers to reach the text content as follows.
Split text in Python by operator[]
To take a part of any text we rely on the digit numbers that are given for each letter in the text.
In the following example, we will display a specific part of the text contained in the variable s.
Actually, we will specify that we want to display all the existing characters starting from field number 11 all the way to before field number 18 .
first example
# contains text s Here we have defined a variable named s = 'welcome to alawiri.com' # s Here we have printed all the characters from the 11th place to the 18th place in the variable print(s[11:18])
• We will get the following result when running.
In the following example, we will display an undefined part of the text contained in the variable s. Actually, we'll specify that we want to display all the existing characters starting from the 11th
digit all the way to the last digits.
second example
# contains text s Here we have defined a variable named s = 'welcome to alawiri.com' # s Here we have printed all the existing characters starting from the number 11 to the last field in the variable print(s[11:])
• We will get the following result when running.
In the following example, we will display an undefined part of the text contained in the variable s.
Actually, we'll specify that we want to display all the existing characters starting from the first block up to before the 11th block .
third example
# contains text s Here we have defined a variable named s = 'welcome to alawiri.com' # s Here we have printed all the characters from the first block up to before the 11th block in the variable print(s[:11])
• We will get the following result when running.
Symbols by which we know the end of a line in Python
The symbol that is placed to indicate the end of a line varies with the types of techniques used to store the data we are dealing with.
The following symbols all mean the end of the line.
| code | meaning in english |
|---|---|
\n |
Line Feed |
\r |
Carriage Return |
\r\n |
Carriage Return + Line Feed |
\v or \x0b |
Line Tabulation |
\f or \x0c |
Form Feed |
\x1c |
File Separator |
\x1d |
Group Separator |
\x1e |
Record Separator |
\x85 |
Next Line (C1 Control Code) |
\u2028 |
Line Separator |
\u2029 |
Paragraph Separator |
In the following example, we will store text in the variable sand put three pointers in it \nto make the text appear on three lines when displayed.
Example
# \n Contains 3 pointers s. Here we have defined a text variable named s = 'This is fist line.\nThis is second line.\nThis is third line.' # which will appear on 3 lines s here we have printed the text in the variable print(s)
• We will get the following result when running.
This is second line.
This is third line.
• Note that the symbol \ndid not appear at the end of each line, but only led to the descent of the line.
note
When you're using your phone or computer, you usually click the button Enterevery time you want to go down to a new line.
What you need to know as a programmer is that the reason to go down on a new line is that a special symbol has been added without your knowledge where you clicked the button Enterto indicate the end of the line. The added symbol is called the end-of-line indicator(End Of Line Flag).
Ready-made functions in the class strto deal with text in Python
The class stris a ready-made class in Python, it contains many functions to deal with the content of texts, whether to search for characters, words or sentences, split the text, change theCaseFor letters, text merging, etc.
We will divide class functions strinto 5 basic categories:
search functions (Searching).
Partition functions(Substring).
Functions to switch (Replacing).
Functions for comparison (Comparison).
Functions for processing(Manipulation).
Information about the str class in Python
When dealing with any function of the class str, whether the explanation of this function says that the function starts from the beginning of the text to the end or starts from its end to the beginning. Always imagine that the text boxes are numbered like this.
to remember
Class stris consideredImmutable classThis means that when you call any function on a text, it will not modify the content of the original text that called it, but will return a modified version of this text and the original text will remain as it is.
Search functions in the class strin Python
| Function name and definition | |
|---|---|
count(sub[, start[, end]])
Returns a number representing the number of times the passed text found the place of the parameter subin the invoked text. |
|
find(sub[, start[, end]])
It searches in the text that called it for the number of the first digit, then finds the same text or letter that we pass to it in place of the parameter suband returns it. If the text to be searched is not found, it will be returned1- . |
|
rfind(sub[, start[, end]])
The difference between it and the function find()is that it starts the search process from the last field in the text that called it to the first field in it. |
|
index(sub[, start[, end]])
It searches in the text that called it for the number of the first digit, then finds the same text or letter that we pass to it in place of the parameter suband returns it. If the text to search is not found, an exception is thrownValueError. |
|
rindex(sub[, start[, end]])
The difference between it and the function index()is that it starts the search process from the last field in the text that called it to the first field in it. |
|
Here we have explained all the search functions in the str class in Python with an example for each function explaining the search functions in detail See examples of search functions in the str class in Python
The hash functions in the class strin Python
| Function name and definition | |
|---|---|
split(sep=None, maxsplit=-1)
Returns a copy of the invoked script divided as a string array. The location of the parameter We seppass a text that specifies the way the text is divided and each section is placed in a single element within the array. |
|
splitlines([keepends])
Returns a copy of the invoked script divided as a string array. Each element in this array is a line in the text. Parameter location keependsYou can pass the value Trueto hold the symbols with which the Python compiler knows how to separate lines and then add each line as an element in the array. |
|
Here we have explained all the hash functions in the str class in Python with an example of each function explaining the hash functions in detail See examples of hash functions in the str class in Python
Toggle functions in the class strin Python
| Function name and definition | |
|---|---|
replace(old, new [, count])
Returns a copy of the text that called it with the replacement of every part in it that matches the text we pass it to it in the place of the parameter with the oldtext we pass it to it in the place of the parameternew. |
|
maketrans(x[, y[, z]])
Used to build a dictionary that can be used to replace text characters with other characters. Note: To apply the dictionary you have prepared to any text, you need to use the function translate(). |
|
translate(table)
Returns a copy of the text that called it with the replacement of some letters of this copy with other letters or its deletion depending on the dictionary that we pass to it in place of the parameter table. Note: The dictionary that we pass to this function is basically built by the function translate(). |
|
Here we have explained all the switch functions in the str class in Python with an example of each function Explaining the switch functions in detail See examples of toggle functions in the str class in Python
Processing functions in the class strin Python
| Function name and definition | |
|---|---|
upper(s)
Returns a copy of the text that we pass to it when invoked in place of the parameter sall capitalized. |
|
lower(s)
Returns a copy of the text that we pass to it when called in place of the parameter sall lowercase. |
|
swapcase()
Returns a copy of the script that called it, with uppercase inverted to lowercase and lowercase to uppercase. |
|
capitalize(s)
Returns a copy of the text that we pass to it when it is called in place of the parameter, swith the first letter in it capitalized. So, this function is useful if you want to start any sentence you want to display with a capital letter. |
|
title(s)
Returns a copy of the text that we pass to it when it is called in place of the parameter, swith the first letter of each word in it converted to a capital letter. So, this function is useful if you are going to display a title, because usually the first letter of each word in the title is capitalized. |
|
join(iterable)
Returns a new text representing the text that called it, embedded in the text or in the array of texts that we pass to it in place of the parameter iterable. |
|
center(width[, fillchar])
Used to display the text that called it in the middle of the line, if it does not exceed the length we specify for the line. In effect, it returns a copy of the text and adds blank spaces around it as needed to make it appear as if it were in the middle.
|
|
expandtabs(tabsize=8)
Returns a copy of the text that called it with double the size of the blank spaces(Tab Spaces)that were added in the text by the symbol \t. By default, the symbol \trepresents 4 blank spaces when displaying text, but in the version returned by the function expandtabs(), each symbol will be converted \tto 8 blank spaces unless you specify the number of spaces yourself. |
|
lstrip()
Returns a copy of the invoked text with any blank space at the beginning removed. |
|
rstrip()
Returns a copy of the invoked text with any blank space at the end removed. |
|
strip([chars])
Returns a copy of the invoked text, omitting any blank space at the beginning and end of it. By default, this function deletes the empty spaces in the first or the end of the text, but if you want to delete certain characters(instead of blank spaces)If they are at the beginning and end of the text, you can pass these characters in place of the parameter chars. |
|
ljust(width[, fillchar])
Returns a copy of the invoked text with blank spaces at the end if the number of characters exceeds the number we pass in place of the parameter width. And you can pass any character or symbol in place of the parameter fillcharto appear instead of blank spaces. |
|
rjust(width[, fillchar])
Returns a copy of the invoked text with blank spaces in its beginning if the number of characters exceeds the number we pass in place of the parameter width. And you can pass any character or symbol in place of the parameter fillcharto appear instead of blank spaces. |
|
Here we have explained all the processing functions in the str class in Python with an example of each function explaining the processing functions in detail See examples of processing functions in Python's str class
Comparison functions in a class strin Python
| Function name and definition | |
|---|---|
startswith(sub[, start[, end]])
Used to find out if the invoked text starts with a specific text or not. Parameter location subYou can pass plain text, or an array of texts of its type tuple. If the parameter text is sub (or the text of one of its elements if it is an array)It is located at the beginning of the text that called it will return True. Otherwise it returns False.
|
|
endswith(suffix[, start[, end]])
Used to find out if the invoked text ends with a specific text or not. Parameter location suffixYou can pass plain text, or an array of texts of its type tuple. If the parameter text is suffix (or the text of one of its elements if it is an array)It is located at the end of the text that called it will return True. Otherwise it returns False.
|
|
isalpha()
Used to find out if the text that called it contains only an alphanumeric character or an alphanumeric character set. Return Trueif it is, otherwise return False. Note: The name of this function is derived from the word"Alphabet"Which means alphabetic characters. |
|
isnumeric()
Used to find out if the text that called it contains only a number or a group of numbers or not. Return Trueif it is, otherwise return False. |
|
isdigit()
Used to find out if the text that called it contains only a number or a group of numbers or not. Return Trueif it is, otherwise return False. Note: This function does not consider symbols that represent numerical values such as the ½ symbol as a number, and this is the difference between them and the function isnumeric(). |
|
isalnum()
Used to find out what type of text characters it called.
|
|
islower()
Used to see if the text that called it contains only lowercase letters(Small Letters)only or not. Return Trueif it is, otherwise return False. |
|
isupper()
Used to see if the text that called it contains only uppercase letters(Capital Letters)only or not. Return Trueif it is, otherwise return False. |
|
istitle()
Used to find out if the first letter of each word in the text that recalled it is a capital letter(Capital Letter)or not. Return Trueif it is, otherwise return False. |
|
isspace()
Used to see if the invoked text contains a blank space(White Space)Or just several blank spaces or not. Return Trueif it is, otherwise return False. |
|
Here we have explained all the comparison functions in the str class in Python with an example of each function explaining the comparison functions in detail See examples of comparison functions in the str class in Python
Operators that are used to work with text in Python
Text Merger +
This operator is used to combine two or more texts and returns them as a new text.
Example
s1 = 'saddam' # consists of one word s1 Here we have defined a text variable named s2 = 'alawiri' # consists of one word s2 Here we have defined a text variable named s3 = s1 + ' ' + s2 # s2 Then we put a blank space, then we put the text in , s1 Here we define a text variable in which we put the text in print(s3) # s3 Here we have printed what was put into the variable
• We will get the following result when running.
Text repetition factor *
This operator is used to repeat the text a specified number of times.
Example
s1 = 'Python '# consists of one word s1 Here we have defined a text variable named s2 = s1 * 5 # s2 five times and we put the final result in the variable s1 here we iterated the text in the variable print(s2) # s2 Here we have printed what was put into the variable
• We will get the following result when running.
The Worker%
This operator is used to combine texts and is often used while displaying the content of any text in an ordered manner where a place is reserved in the text for values that were previously stored in variables.
Example
name = 'saddam' # We have stored a text value of name in the variable
money = 10 # We store an integer value of money in the variable
subject = 'programming' # We have stored a text value subject in the variable
age = 19 # We have stored an integer value of age in the variable
# which we intend to display in its place of name to reserve a place for the text in the variable %s here we used the symbol
print('Hello my name is %s.' %(name))
# Which we intend to display in its place money to reserve a place for the number in the variable %d here we used the symbol
print('I have %d dollars.' %(money))
# age to reserve a place for the number in the variable %d and the code subject to reserve a place for the text in the variable %s Here we used the code
print('I learn %s at %d.' %(subject, age))
• We will get the following result when running.
I have 10 dollars.
I learn Programming at 19.
The Workerin
This operator is used to find out if the text contains a specific word or sentence in it, returning Trueif it is and Falseif it is not.
Example
s = 'Python is easy to learn.' # s Here we have defined a text variable named
print('easy' in s) # s is in the text stored in the variable 'easy' because the text is True here we will print
print('hard' in s) # s does not exist in the text stored in the variable 'hard' because the text is False here we will print
• We will get the following result when running.
False
The Workernot in
This operator is used to find out if the text does not contain a specific word or sentence in it, where it returns Trueif it is and Falseif it is not.
Example
s = 'Python is easy to learn.' # s Here we have defined a text variable named
print('easy' not in s) # s is in the text stored in the variable 'easy' because the text is False here we will print
print('hard' not in s) # s does not exist in the text stored in the variable 'hard' because the text is True here we will print
• We will get the following result when running.
False