Strings in Python Part-2
Hi everyone this is part-2 on strings. And if you haven’t gone through the 1st part I would recommend you to first go through part-1 before jumping on to part-2. so let’s not delay and start with our part-2 discussion on strings.
How to modify a string?
Python has a set of built-in methods which we can use on strings.
For example:
Upper Case : It returns the string in upper case.
Lower Case : It returns the string in lower case.
What the whitespace and How to remove a whitespace?
- whitespaces are before/after the actual text.
- To remove whitespaces from beginning or end.
we have strip() method.
Many time we have need to replace a particular part with existing information. How to address this issue?
In Python we have replace( ) method.
- This method takes max 3 argument str.replace(old, new [, count])
- old — the existing one which we want to replace.
- new — this will replace the old one.
- count(optional) — this tells how many times you want to replace old with new one.
It’s important to remember that this function will replace every instance of the old string with the new string if the count is left blank.
Another important method is Split Method
- It splits the string into substrings and returns a list where the text between the specified separator becomes the list item.
The syntax of split()
is:
str.split(separator, maxsplit) # BOTH THIS PARAMETER ARE OPTIONAL1
without passing a parameter:
Formatting with the .format() method
String.format() is a useful function for formatting objects in your strings for print statements ()
syntax:
‘string here{} then also{}’.format(‘something1’,’something2')
Float formatting Follows’’{value:width.percision f}’’
value : it is the variable which we will assign
width: it is nothing but the whitespaces.
.precision f : it is numbers which we want after the decimal place
For example:
Formatted String Literals (f-strings)
- Over the more traditional .format() string method described above, f-strings, which were introduced in Python 3.6, have many advantages.
- One benefit is that you can insert external variables directly into the string rather than passing them through as arguments. format(var).
- For Example:
I’ve covered some crucial strings techniques that are frequently used. However, you can practice a lot more techniques by clicking the link and going at your own pace.