Professional Documents
Culture Documents
Lecture On Strings
Lecture On Strings
In Python, the way we store something like a word, a sentence, or even a whole
paragraph is as a string. A string is a sequence of characters contained within a
pair of single quotes or double-quotes. A string can be any length and can
contain any letters, numbers, symbols, and spaces.
In this lesson, we will learn more about strings and how they are treated in
Python. We will learn how to slice strings, select specific characters from strings,
search strings for characters, iterate through strings, and use strings in
conditional statements.
We can select specific letters from this string using the index. Let’s look at
the first letter of the string.
print(learning_python[1])
# (Output: e ) because e is at 1 index, remember that python is 0 indexed.
python = learning_python[9:-1]
To know the size of the string we use len ( ) we write the variable name
inside the parenthesis
Which will give us True, similarly we can find any characters in string.
Moving String 1 side to the left and right is somehow very tricky to get. We
use the following commands :
ADVANCE STRING METHODS IN PYTHON :
1. FORMATTINGING METHOD :
.title() returns the string in the title case, which means the first letter
of each word is capitalized.
2. SPLITTING STRINGS :
. split() is performed on a string, takes one argument, and returns a list
of substrings found between the given argument (which in the case
of .split() is known as the delimiter).
- Providing the delimiter for a .split will tell us from where our string will be
divided into items of the list.
- Delimiter itself will not be included in the list.
'delimiter'.join(list_you_want_to_join)
Here delimiter is the thing you want to have between the items when they are
converted into a string. For example, if you want # between all of the list items when
they are converted in the string you use # in place of delimiter or you want to have
space between items so you just leave it empty ‘ ‘.
.replace(). Replace takes two arguments and replaces all instances of the
first argument is a string with the second argument. The syntax is as follows
string_name.replace(substring_being_replaced, new_substring)
Here’s an example:
print('smooth'.find('t'))
# => '4'
7. FORMATTING A STRING :
EXTRA LEARNING :
To remove duplicate items from a list :
Variable = list(dict.fromkeys(list_name)