part4: strings

Learn Python Through Anime: Strings

If you are new here, then consider checking out the previous three articles on Learn Python Series. String will be

Strings In Python

You already know what strings are. Anything enclosed within double/single quotes in Python is considered to be String. The actual definition of Strings is “The sequence of characters enclosed within quotes”. 

protagonist = "Natsu Dragneel"
print(type(protagonist))
<class 'str'>

Where str denotes String Data Type.

Note: All variables and also Sting values are case sensitive e.g., name and Name are treated differently.

Basic String Methods

len()

The length function len() is used to return the total number of words in the string. Note: len() cannot be used for integer or float data types.

Syntax:
len("<any string value>")
>>>arc_name = "Enies Lobby"  #even the whitespace is included
>>>len(arc_name)
11

>>>website_viewers = None
>>>len(website_viewers)
TypeError: object of type 'NoneType' has no len()

>>>berserk_total_chapter = 360
>>>len(berserk_total_chapter)
TypeError: object of type 'int' has no len()

>>> number = ‘0’
>>> len(number)
1

count()

count function is used to return the total frequency of the specified string. By frequency, I mean a total number of occurrences of the same variables.

Syntax:
variable_name = "<any string value>"
print(variable_name.count(‘any string value’))
return type <class ‘int’>
>>>arc_name = "Chunin Exam" 
>>>arc_name.count(‘n’)
2
>>>arc_name.count(‘Ramen’) 
0
>>>arc_name.count(‘m’) 
1
>>> anime = "Hunter x Hunter"
>>> anime.count('Hunter')
2

index()

index() is the most important in programming. An index is a place where the variable is located. In Programming the indexing starts from 0. Not mis-confuse the index count with length count. In an() we see the total number of words whereas in the index() we find the character index starting the count from zero.

Syntax: 
string_variable_name.index(string_value)
return type <class ‘int’>
>>>name = “Light Yagami”
>>>name.index(‘g’)
2
>>>name.index(‘i’)   #there are two i in the name, the first i index will be executed
1
>>>name.index(‘i’,5) #finds next i in name after 5th index
11
>>>name.index(‘k’)
ValueError: substring not found

As of now, we know that the indexing starts with 0. The maximum position of the index is n-1. Where n is the total number of lengths. Now, what if the situation arrives where there are multiple letters inside the string. In the above example, Light Yagami has two ‘i’, if you ask the index, it’s obvious the first ‘i’ from the name will be executed. In those times you can add another parameter and tell the interpreter to search for index ’i’ from the given position.

upper() and lower()

upper() and lower() are conversion function. By using upper() function you can convert all the characters of the given string into upper case characters[A-Z]. So now you can figure out what lower() does. lower() function converts all the characters into lower case characters[a-z].

>>> survey_crops = “Levi”
>>> surey_crops.upper()
‘LEVI’
>>> survey_crops.lower()
‘levi’
>>> name = input(“Enter your name:").lower()
Enter your name:Okabe Rintaro
>>>print(name)
‘okabe rintaro’

startswith() and endswith()

With the name goes startswith() and endswith() are used to compare the beginning and ending of the given string based on the pattern provided as the parameter inside the function.

>>>name = “Oreki”
>>>name.startwith(‘O’)
True
>>>name.startwith(‘o’)
False
>>>name.endswith(‘I’)
False
>>>name.endswith(‘i’)
True
>>>permission = input(“Are you sure?(y/n): ").lower()
Are you sure?(y/n): y
>>>permission.startswith(‘n’)
False
>>> 'roronoa Zoro'.startswith('Roronoa')
False
>>> 'roronoa Zoro'.startswith('roronoa')
True

strip()

We now know that even blank spaces are counted for indexing and this might even affect word length. Sometimes we do require to count this blank space, but most of the time by human error we give extra space somewhere, where we should not be providing. Thus using the strip() function you can strip the whitespace from the given string,

>>>detective = "    Rampo   "
>>>detective.strip()
“Rampo”
>>> agency = “Dazai and Atsushi”
>>> agency.strip()
Dazai and Atsushi
>>>  ex_port_mafia = "     Dazai“.strip()
>>> ex_port_mafia
Dazai
>>> strong = “whitetiger      ".strip()
>>>strong
whitetiger

replace()

replace() function is used to interchange between two values. If you need to change any letter from a string value you can do it with help of replace() function.

>>> karasuno = "Hinata and Kageyama"
>>> karasuno.replace("and","Tsukishima")
'Hinata Tsukishima Kageyama'

replace() has a simple syntax. It takes two parameters, the first parameter is the value to be replaced(existing) and the second parameter is replacing or new value. In the above example and is replaced with Tsukishima. More examples to look at:

>>> pirate_hunter = “Roronoa Zoro”
>>> pirate_hunter.replace(“Roronoa”,”Shimotsuki”)
‘Shimotsuki Zoro’
>>> chef = “Black leg Sanji”
>>> chef.replace(“Black leg”,”Vinsmoke”)
‘Vinsmoke Sanji’

find()

find() is a concept related to searching. There are various methods to perform search algorithms. find() is one of the easiest ways to search for certain elements in the string. Find() operation will be used more often when we start dealing with files.

>>> lost = "Roronoa Zoro" #type 1: Find a word
>>> lost.find("Zoro")
8 
>>> lost.find("zoro")  #type2: it will return -1 if element is not present
-1
>>> lost.find("o")  #type3: find a single character
1
>>> lost.find("o",7)
9
>>> lost.find("o",6)  
9
>>> lost.find("o",5) 
5

Difference Between find() And index()

Let’s analyze what find() does. We have already discussed index(), now that we know how the index works, find does almost the same. Find and index both return an integer value i.e., the index of the given element. But why need to find() when we already have an index(). But there is one big difference here to observe. When the given element is not in the string, the index returns a ValueError whereas find() returns -1. Rest syntax of the find is similar to the index. We provide a second parameter an integer i.e., a substring to find the index after the specified location. You will have a clear view of the find while working with files.

isX()

isX, where X stands for alpha(), digit(), alnum(), upper(), lower(), space() with is as the prefix. This function returns Boolean type i.e., True or False. Is here is used to check whether the specified string matches the X.

>>> unique = "Mushishi"
>>> unique.islower()
False
>>> unique.isupper()
False
>>> unique.isalpha()
True
>>> unique.isalnum()
True
>>> unique.isdigit()
False
>>> age = 34
>>> age.isalnum()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'isalnum'
>>> age = '34'
>>> age.isalnum()
True
>>> age.isdigit()
True
>>> height = "134.96"
>>> height.isdecimal()
False
>>> height.isnumeric()
False
>>> height.isdigit()
False
>>> age = "21"
>>> age.isdigit()
True

format()

This is one of the most useful shorts cut we should have used from the beginning, but this is the right time to introduce it. So far we have been printing multiple values inside the print() statement separated by a comma, i.e.,

>>>name1= “Lelouch”
>>>name2= “Suzaku”
>>>print(“Main Character:",name1,"|| Side Character:",name2)

Now we have used way too many comma and quotes in the program. Now let us break this down using format() operation.

captain = "Luffy"
vice = "Zoro"
chef = "Sanji"
navigator = "Nami"
sniper_god = "Usopp"
print("Straw Hat Pirates:")
print(" Captain:{} \n Vice Captain{} \n Navigator:{} \n Chef:{} \n Sniper: {}".format(captain,vice,navigator,chef,sniper_god))

Straw Hat Pirates:
 Captain:Luffy 
 Vice CaptainZoro 
 Navigator:Nami 
 Chef:Sanji 
 Sniper: Usopp

Format Operator In Python

The format operator, % allows us to construct strings, replacing parts of the strings with the data stored in variables. Let’s take a visit to the C Programming language. While printing the integer values we used “%d”, “%f” for float, and “%s” for string.

Syntax:
"%d”%variable_name: For Interger → int to str
"%f”%variable_name : For Float → float to str
"%g”%variable_name: For Exact Float ValueError → float to str
"%s”%variable_name: For String → str to str
>>>episode = 12
>>> "No Game No Life has total %d episodes"%episode
'No Game No Life has total 12 episodes'
>>> episode_new = "%d"%episode
>>> type(episode_new)
<class 'str'>
>>> type(episode)
<class 'int'>

>>> height = 165.78
>>> float(height)
165.78
>>> "His Height is %fcm."%height   #Use of %f → float to str 
'His Height is 165.780000cm.'
>>> "His Height is %gcm."%height   #Use of %g → float to str 
'His Height is 165.78cm.'
>>> new_height = "%f"%height
>>> type(new_height)14 pt
<class 'str'>
>>> type(height)
<class 'float'>

String Indexing

String Indexing, index you again. We have already mentioned the index() and find() an operation that returns the string index. And there is more in String indexing. So far what we have seen is we mention a string value to get an index that returns integer data type. But we haven’t discussed vice-versa, have we?

Now we will discuss string index where we mention integer value and in return, we get String data type as an output.

>>> joi_rebels = "Katsura Kotaru"
>>> joi_rebels[0]
'K'
>>> joi_rebels[10]
't'
>>> joi_rebels[5]
'r'
>>> joi_rebels[20]
IndexError: string index out of range

String Slicing

Now that we have seen String Indexing in detail. But there is one thing missing. I hope you get this doubt: While performing index() and find(), we use to string a single character as well an entire word. By single character I mean the index of (‘a’) and by entire word means (“Great”). Now while performing String indexing using Integer value we were only able to return a single character. What if we need to return a word? Let’s dig into it.

Slicing in Python is to cut short the variable. Now say there is a large name, which you need to slice down, you shall usually start from one point and end at some point. Now, what does this mean?

Consider an example, name= “Hijikata Toshiro”, now say you want to just print Toshiro. How will you do that? This is where Slicing comes into the Picture.

police = "Hijikata Toshiro"
>>> police.index('Toshiro')
9
>>> police[9:16]
'Toshiro'
>>> police[]
SyntaxError: invalid syntax
>>> police[:]
'Hijikata Toshiro'

#using step in slicing
>>> simple_string = "0123456789"
>>> simple_string[2:9:2]
'2468'
>>> simple_string[3:9:2]
'357'

#omiting indexes
>>> yato_clan = "Kamui and Kagura"
>>> yato_clan[:6]
'Kamui '
>>> yato_clan[:5]
'Kamui'
>>> yato_clan[8:]
'd Kagura'
>>> yato_clan[:]
'Kamui and Kagura'
>>> yato_clan[:7]
'Kamui a'
#reverse of the string

>>> yato_clan[::-1]
'arugaK dna iumaK'
>>> yato_clan[5::-1]
' iumaK'

String Is immutable

Immutable is something that you can’t change once assigned. We have seen assigning different values for the same variable but we are not talking about that. The string is immutable so once you have assigned a value to a variable you can’t change that assigned value.

>>> founding_titan = "Eren Yeager"
>>> founding_titan[5:]="Jeager"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> founding_titan[0]
'E'
>>> founding_titan[0]='e'
TypeError: 'str' object does not support item assignment

String is Iterable

>>> captain = "Levi"
>>> for letters in captain:
...  print(letters)
... 
L
e
v
i
>>> for letters in range(len(captain)):
...  print(captain[letters])
... 
L
e
v
I

in and not in operation

It is mainly used to prompt if the number is in range and it returns either True or False. Let me repeat it again, it returns either True or False. You have your answer. In and not in are used to return a Boolean data type.

>>> bleach = "ichigo uryu urahara renji rukia"
>>> 'luffy' in bleach
False
>>> 'ichigo' in bleach
True
>>> 'naruto' in bleach
False
>>> bleach = "ichigo uryu urahara renji rukia"
>>> 'luffy'not in bleach
True
>>> 'ichigo' not in bleach
False
>>> 'naruto' not in bleach
True

Multi-line Comment

""" This is ignored
Rules
1. Variable should not start with a number
2. No special character should be used in variable except underscore(‘_’)
3. No whitespace can be used in variable
4. Variable can be any word even if has no meaning
"""
hero = "Saitama"
print(hero)

Output:
Saitama

Conclusion

You can try 30 Days Python Programming by solving amazing code daily. Anime Vyuh Github Organization has a public repo, which will help you with #30DaysOfPython.

If you like our content, support us by Buying a Coffee.