Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

STRINGS IN PYTHON

Words and sentences are fundamental to how we communicate, so it follows that


we’d want our computers to be able to work with words and sentences as well.

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.

Consider a string: Learning_python = “Learning Python”

 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.

 Slicing a string means dividing it from index to index. For example, if we


want to fetch python from learning_python, we know that it is from index 9
to the last variable. ( format is string[first_index:last_index] )

python = learning_python[9:-1]

 To know the size of the string we use len ( ) we write the variable name
inside the parenthesis

 This is because strings are immutable. This means that we cannot change a


string once it is created. We can use it to create other strings, but we
cannot change the string itself.
 If we want to use single or double-quotes in our string we can only use it
using ( \” string / ” )

 The concept of a negative index is a bit tricky to learn. But it is useful in


selecting the last values of string or list or whatever data type we are
working.

 Consider a string x = “123456789”, to get the last three numbers we will


apply,
last_three = x[-3:0], means from -3 index print to 0, which means obviously
0 being included. And if we want to print everything but the last three we
will use exclude_last_three = x.[0:-3]. Similarly, if we want to print indexes
from between like 3456, between = x[-7:-3]

 Concept of finding a string in a string: we can use loops to find something


present in a string or not but there is a simple command that we can use
for example we have x= “Pakistan” and y = “Pak”, we will use:

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 :

 .lower() returns the string with all lowercase characters.

 .upper() returns the string with all uppercase characters.

 .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).

The following syntax should be used:


string_name.split(delimiter)
Delimiter: a character that marks the beginning or end of a unit of data.
(If you do not provide an argument for .split() it will default to splitting at spaces.)

For example, consider the following strings:

man_its_a_hot_one = "Like seven inches from the midday sun"


print(man_its_a_hot_one.split())

Output => ['Like', 'seven', 'inches', 'from', 'the', 'midday', 'sun']


.split returned a list with each word in the string.
 If we provide an argument for .split() we can dictate the character we
want our string to be split on. This argument should be provided as a
string itself.

- 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.

3. JOINING A STRING TO FROM A LIST


we can convert a list into a string just like we converted a string into a list,
we will use .join ( )

The syntax of .join() is:

'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 ‘ ‘.

4. REMOVING WHITESPACES FROM STRINGS

 Python provides a great method for cleaning strings: .strip(). Stripping a


string removes all whitespace characters from the beginning and end.

Consider the following example:

featuring = " rob thomas "


print(featuring.strip())
# => 'rob thomas'
If we want to strip two items we will use .strip() two times.
For example, we want !!!! and white spaces both to be removed we use:
name.strip(‘!’)strip()
 You can also use .strip() with a character argument, which will strip that
character from either end of the string.

Consider the example :

featuring = "!!!rob thomas !!!!!"


print(featuring.strip('!'))
# => 'rob thomas '
By including the argument '!' we are able to strip all of the! characters from either side
of the string. Notice that now that we’ve included an argument we are no longer
stripping whitespace, we are ONLY stripping the argument.

5. REPLACING INSTANCES OF STRING :

.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)

6. FINDING SOMETHING IN A STRING:

Another interesting string method is .find(). .find() takes a string as an


argument and searches the string it was run on for that string. It then
returns the first index value where that string is located.

Here’s an example:

print('smooth'.find('t'))
# => '4'
7. FORMATTING A STRING :

Python also provides a handy string method for including variables in


strings. This method is .format(). .format() takes variables as an argument
and includes them in the string that it is run on. You include {} marks as
placeholders for where those variables will be imported.

Consider the following function:

def favorite_song_statement(song, artist):


return "My favorite song is {} by {}.".format(song, artist)

we call the function,


favorite_song_statmenet(“you are my fire”,” Disneyland”).

Output => “My favorite song is you are my fire by Disneyland”

For more legitimate code:

def favorite_song_statement(song, artist):


return "My favorite song is {song} by {artist}.".format(song=song,
artist=artist)
# for this you have to predefined the variables.

EXTRA LEARNING :
To remove duplicate items from a list :
Variable = list(dict.fromkeys(list_name)

You might also like