Python3 tutorial - 15 (String formatting)

Welcome to CCP
Let's get started !

So, we left off with some magic methods and decorators,
Now lets discuss about Strings,

As we know,
Strings are written b/w quotes and can be formatted,
this formatting is done by string's built-in format() method,

like this:


or like this:


There are many ways to format the string other than the format() method also,

like this one:



This way, we are concatenating or joining the strings where we have to keep in mind about spaces to join them,

But as usual, if we use this way and suppose the name variable stored is an integral type value, then, it would give us an error which is caused to joining string and a number regardless it is integer or floating point, it will give us an error,

To prevent the error, we have to first convert the number into a string as we can only concatenate two or more strings and not strings with numbers,

then,
it would look like this:


Whereas,
format() method of strings doesn't need this conversion,
It does all things and you have to just focus on what to and where to place in the string,

One more basic way of doing this is:


But it is only used to print and format at the same time,
If you want to parse or manipulate the string, then the best way of doing this is either by concatenation or using format() method,

Now,
lets move on to string indexing and slicing,
Have a look at this:


Do you remember that these string methods are very similar to the one we've used in lists or tuples along with the indexing,

That's the surprise,
strings can be also sliced like lists


This slicing happens all b/w the "[]" in which we declare starting step before ":" (which is inclusive) and the ending step after ":" (which is exclusive),

I hope you understood,
You can do more than this,
These were very small Illustrations,
You can even extract linear data from easy lines using this technique,

Now lets move on to string methods,

There are some important string methods which are very much used,

These are:
1. strip() (removes surrounding spaces and newline characters from string)

2. lstrip() (strips strings only from left)

3. rstrip() (strips strings only from right)

4. replace(old_string, new_string) (replaces an old part with a new part)

5. lower() (converts whole string in lower case)

6. upper() (converts whole string in upper case)

7. isnumeric() (returns True or False if the string is full of numbers)

8. isalpha() (returns True or False if the string is contained full of alphabets and no numbers)

I hope you understood,

Note: these all string methods return a converted string, so you need to declare a variable to store the converted string

SEE YOU LATER !

Comments