In the previous post, we learned a lot about strings in python. But there are still a few important things left.
We will cover them and an exciting challenge that will help you boost your python skills and test them. Read it till the end as the last function will make you laugh😅.
Contents
Previous post’s challenge’s solution
I have shown solutions to all five questions using positive indexes you can use negative indexes if you want to.
answer – 1
Slice the word until first “e”.(Typ)
word = 'Typesetting'
ans1 = word[:3]
#Another way:- word[0:3]
print(ans1)
#output: Typ
We want the letters till the first e
excluding it. This means that our stop value would be the index of e
,i.e, 3
.
We want to take all the letters from the beginning due to that the start value would be nothing or 0
.
And as we don’t want any step the step value would be 1
or nothing.
answer – 2
Get “sum” out of the string. (sum)
find_sum = 'Lorem Ipsum'
ans2 = find_sum[8:]
# Another way:- find_sum[8:11]
print(ans2)
#Output should be sum
From the string, we first need to know the index of s
. It’s 8
. So 8
is our start value. And we want the rest of the letters as it is, for this, the stop value can be nothing or 11
(10+1).
No step is required so it can be 1
or nothing.
answer – 3
Get “can”.
wrd="Toscana"
ans3 =wrd[3:6]
print(ans3)
#Output should be can
Here, c
has the index number 3
which is why the start value is 3.
And n
has the index number 5
which is why we took 6
as the stop value because we want to include n
. And you can use 1
or nothing for step value.
answer – 4
Can you slice the word from beginning to the end with steps of 2 (excluding the last two characters.)?
word="standard"
ans4 = word[:6:2]
#Another way:- word[0:6:2]
print(ans4)
#Output should be sad
Here, we don’t want to include the last two values which is why we will take the index number of the second last value as the stop value.
There is no mention of where to start so we will start from the beginning for that the start value will either be 0
or nothing.
And finally, we are asked to take 2
the step value.
answer – 5
Slice the word to get “tan”.
word="standard"
ans5 = word[1:4]
print(ans5)
#Output should be tan
Here, t
has the index number 1
which is why the start value is 1.
And n
has the index number 3
which is why we took 4
as the stop value because we want to include n
. And you can use 1
or nothing for step value.
NOTE:- your approach from now on can be different for solving problems but if your output is the same then you can be sure that your approach is correct.
Escape sequences
Have you ever wondered how can you use characters like,'
,"
, etc in your strings?
Well, that’s what escape sequences help you in. These characters are illegal in a string to use them you need to use a backslash \
in your string here’s how:-
str1 = "They said \"python is awesome\" "
print(str1)
Output:-
They said "python is awesome"
If you would have tried to use these " "
inside a string enclosed in these " "
without a \
you would get an error like this:-
File "c:Userstest.py", line 1
str1 = "They said "python is awesome" "
^^^^^^
SyntaxError: invalid syntax
Here’s a list of some escape sequences in python. (if you want to know more click here.)
Escape Sequence Character | What It Does | code |
---|---|---|
\\ | displays one backslash | print("hi\hello") #hi\hello |
” or ‘ | to print single or double quotes | print("hi\"hello") #hi"hello |
\n | to print a new line. eg. | print("hi\nhello") |
\t | to print a tab(space). eg. | print("hi\thello") |
\b | to print a backspace. eg. | print("hi\bhello") |
Strings methods/functions
Now let us see some of the exciting 🤩functions that the string class has. We have already used one function here when we were learning how to use strings in variables.
Especially wait for the last one it will blow 🤯 you.
upper()
This method is like a magic spell 🧙♀️ when used turns all the characters of the given string into capital cases.
You’ll get it better with an example:
str1 = "i want to grow tall"
print(str1)
print(str1.upper())
#NOTE:- this won't make changes in the original string as strings are immutable
#To read more on immutable: https://python-hub.com/strings-in-python-with-an-exciting%e2%9c%a8-challenge-part-1/#are-they-mutable
Output:-
i want to grow tall
I WANT TO GROW TALL
lower()
This magic spell 🧙♀️ is just the opposite of the previous spell. It turns all the characters of the given string into lowercase.
For example:-
str1 = "TURN ME SMALL AGAIN THIS DOES NOT FEEL GOOD"
print(str1)
print(str1.lower())
#NOTE:- this won't make changes in the original string as strings are immutable
Output:-
TURN ME SMALL AGAIN THIS DOES NOT FEEL GOOD
turn me small again this does not feel good
Len()
This function is like that head boy/girl of the class who used to count the number of children👩🦰 present in the class.
This function counts the number of characters present in the string.
Example:-
str1 = "Tell me how many characters do I have?"
print(str1)
print(len(str1))
#NOTE:- This function is used bit differently from the previous ones
Output:-
Tell me how many characters do I have?
38
join()
To explain this function I will introduce you briefly to two new data types:
- lists and
- tuples.
The list is a data type that contains some sequence in a comma-separated form enclosed inside two square brackets.
Tuples are the same as the lists only difference is that they are immutable like strings whereas lists are mutable. Tuples are either not enclosed in any brackets or are enclosed in parentheses (round brackets).
And yes, if I forgot to tell you a string is a sequence of characters.
That’s enough for now about these two data types.
join function joins elements of lists or tuples by different separators, and turns them into a string.
An example would make this clear.
List1 =["hi", "my", "name", "is", "python"]
print(List1)
print("_".join(List1))
#NOTE:- You can use anything inside the quotes before
#the join function instead of this "_". And you can put
#a tuple too inside the join function.
#A List1 is just a variable name.
#You can use any other valid variable name.
Output:-
['hi', 'my', 'name', 'is', 'python']
hi_my_name_is_python
split()
The join function turns a sequence into a string and this function turns a string into a list.
See the example below:-
name = "YourName"
str1 = f"Hi-I-am-a-super-powerful-program-made-by-{name}-that's-why-I-cost-10-million-dollars"
print(str1.split("-"))
Output:-
['Hi', 'I', 'am', 'a', 'super', 'powerful', 'program', 'made', 'by', 'YourName', "that's", 'why', 'I', 'cost', '10', 'million', 'dollars']
replace()
Now, I know that when you got to know that strings are immutable your plan to play a prank on your friend by changing his speech stored in a python string flopped😒😟. But, don’t get disheartened you have still an hour left before his address gets started and the best part is that he does not remember it.
So, here’s how you can spoil😜😝😅 it using the replace function.
friend_s_speech = '''I am a very cool person. And all of you should be cool in any given situation.
Be cool if teacher scolds you see where are you not being good enough.
Be cool if your friends tease you.
In the end keep calm and be cool'''
Here's the spoiler
friend_s_speech = friend_s_speech.replace("cool", "fool")
print(friend_s_speech)
Output:-
I am a very fool person. And all of you should be fool in any given situation.
Be fool if teacher scolds you see where are you not being good enough.
Be fool if your friends tease you.
In the end keep calm and be fool
Note: All string methods return new values. They do not change the original string.
Hope that these functions were as fun to you as they are to me and you enjoyed pranking your friend.😅
Conclusion
In this post, we saw that escape sequences do not mean a python’s ability to free prisoners from jail😅. They are used to print special🎇 characters in strings.
We also saw some exciting functions/methods that the string class offers us.
Challenge🧗♀️
Finally time for the exciting challenge that you and I have been waiting for since the last post.
🎉You will be given a comma-separated sequence/string by the user(This means you would have to take input from your user).
You first have to convert all of its characters to capital cases.
Then, you need to print the total number of characters in the sequence/string.
And finally, you need to print the sequence/string in a full-stop separated format.🎉
Here’s an example:-
Input sequence/string :-
i,love,python
Output sequence/string :-
13
I.LOVE.PYTHON
This challenge can be difficult to solve if it does follow these steps:-
- First, get clear with the functions(Hint:- split and join) above. >> Then search for the function that enables you to take input in python.
- Now, break your program into simple steps:
- taking string input of the sequence
- converting it into upper case (upper)
- counting the no. of characters (len)
- removing commas (split, string to list)
- adding full stops (join, list to string)
- And lastly don’t give up and keep on trying. You can do it.
Go fast. I am waiting. Comment your answers below.
This was it for the post. Comment below suggestions if there and tell me whether you liked it or not. Do consider sharing this with your friends.
See you in the next post till then have a great time.😊Bye bye👋
To read the next post click here.