More with Strings

So far, we have covered a lot of different concepts and have dived into their respective specialized features and use cases. In everyday life, one thing we usually deal with is raw text, and to make sure we can work well with it, this chapter is introduced. This chapter will help us understand the power of String manipulation with Python and further strengthen our core programming knowledge.

Escape characters in Python

Let's start with the basics. We will begin with escape characters. What do they mean? Some characters in Python can get mixed with the Python syntax, resulting in an unexpected output. To make sure this doesn't happen, we use escape characters. For example, lets consider typing: What is your mother's maiden name?

You can type the following code on the Python interpretor (black box) on your Repl window.

>>> 'What is your mother's maiden name?'

But this will give us a SyntaxError error:

  File "<ipython-input-3-fb677048ae0b>", line 1
    'What is your mother's maiden name'
                         ^
SyntaxError: invalid syntax

So, how do we approach this? Well, we could use double quotes:

>>> "What is your mother's maiden name"
"What is your mother's maiden name"

This works! How about this?

>>> "I want to use a double quote(") in my statement"

Do you think it will work? Actually, it won't. Once again, we get a SyntaxError.

  File "<ipython-input-5-44051f4eedfb>", line 1
    "I want to use a double quote(") in my statement"
                                   ^
SyntaxError: invalid syntax

This is why we need Escape Characters. To use a single quote, we can use \' instead of the '.

>>> 'What is your mother\'s maiden name'
"What is your mother's maiden name"

It works! Similar to this, we have several escape characters:

Escape Character syntax Equivalent logical meaning
\' Single Quote
\" Doubt Quote
\n New line (line break)
\ Back Slash
\t Tab

PRO TIP: What if you don't want to have the double quotes in the output? This is how an output looks like usually: "What is your mother's maiden name?". You can try to put a r before the quotations while printing it and the output won't have the quotes. This is called Raw output. Run this: print(r"What is your mother's maiden name?").

Slicing Strings

This might sound a bit similar. If we go back into the course, we did List slicing before. This is exactly the same concept, just applied on a String, instead of multiple Strings. Lets recall one simple concept before getting further into this:

For a String What is your name?, the index starts at 0 with the letter W taking that place. It goes to the last letter and stops. Hence, a String of size 10 has index ranging from 0 to 9.

The syntax is also similar:

  • If there is just one argument, then it's to call the letter at that index in the String.
  • For a negative argument, we start from the last letter in the String.
  • For two arguments, the first one is the Start, and the second one is the Stop, where we don't include the letter at the Stop index.

Lets try these out:

>>> example = 'This is my name'
>>> example[3]
's'
>>> example[-2]
'm'
>>> example[2:10]
'is is my'

String methods

We have discussed methods for Lists and Dictionaries and understood how useful they are. Now we will study String methods that help us making our program more efficient and fast. They are quite easy to understand and similar to what we have done so far.

The capitalize() method

This method capitalizes the first letter of the String.

>>> example = "what is your name?"
>>> example.capitalize()
'What is your name?'

The isalpha() and isdigit() methods

  • The isalpha() mtthod is used to check if the String has atleast 1 character and all alphabetic characters. If yes, it returns True, otherwise False.
  • Similarly, isdigit() method is used to check if the String has atleast 1 character and all digits. If yes, it returns True, otherwise False.
>>> example = "what is your name?" # -> Spaces and special characters not allowed
>>> example.isalpha()
False
>>> example.isdigit()
False
>>> example = "helloWorld"
>>> example.isalpha()
True
>>> newExample = '12345'
>>> newExample.isdigit()
True

The isupper(), islower(), upper() and lower() methods

These methods are interlinked with each other. As you can guess, they literally mean what they say.

  • isupper() method is used to check if the characters in a String are in Upper case or not. If yes, it returns True, otherwise False.
  • islower() method is used to check if the characters in a String are in Lower case or not. If yes, it returns True, otherwise False.
  • upper() method converts all the alphabetical letters in a String to the Upper case.
  • lower() method converts all the alphabetical letters in a String to the Lower case.
>>> example = 'This is my name'
>>>    example.isupper()
False
>>>    example.islower()
False
>>>    example.upper()
'THIS IS MY NAME'
>>>    example.lower()
'this is my name'

The rstrip(), lstrip() and strip() methods

Often we have a lot of Whitespace in Strings, and to remove that, we use these methods.

  • rstrip() method removes whitespace from the right side from the end of the characters to the quotation mark.
  • lstrip() method removes whitespace from the left side from the quoatation mark to the first character.
  • strip() method removes whitespace between the quoatation mark and first character, and last character and the quoatation mark.
>>>    example = '  This is my name   '
>>>    example.rstrip()
'  This is my name'
>>>    example.lstrip()
'This is my name   '
>>>    example.strip()
This is my name'

TASK: Research on other String methods and run them using any examples. It is important to learn how to do self research when it comes to programming. As a programmer, we often face hurdles, and its good to be self sufficient!

results matching ""

    No results matching ""