Skip to main content

Python - String Functions - Changing Case, Location, Counting, Formatting, Checking, Regular Expressions

🐍 Some of the String Functions include the following:


  • .capitalize() 
  • .upper() 
  • .lower() 
  • .title() 
  • .count() 
  • .find() 
  • .center() 
  • .expandtabs() 
  • .isalnum() 
  • .isalpha() 
  • .islower() 
  • .isspace() 
  • .istitle() 
  • .isupper() 
  • .endswith()
  • .split()
  • .partition() 
Let's take an example string and apply all methods on it.
s = 'hello 1st World, 2nd World, and 3rd World.'

Changing case

Capitalize

s.capitalize()
Output:
'Hello 1st world, 2nd world, and 3rd world'
It capitalizes the first letter of the string for that output alone.

Uppercase

s.upper()
Output:
'HELLO 1ST WORLD, 2ND WORLD, AND 3RD WORLD'
It converts entire string into upper-case for that output alone.

Lowercase

s.lower()
Output:
'hello 1st world, 2nd world, and 3rd world'
It converts entire string into lower-case for that output alone.

Location and Counting

Count

s.count('o')
Output:
4
It counts number of occurrences of the string passed in the string 's' and returns the count.
s.count('world')
Output:
3
It counts number of occurrences of the string passed in the string 's' and returns the count.

Find

s.find('o')
Output:
4
Returns the location of the first occurrence of the string passed in the string 's'.
s.find('world')
Output:
10
Returns the location of the first occurrence of the string passed in the string 's'.

Formatting

Center

s.center(50, '#')
Output:
'####hello 1st world, 2nd world, and 3rd world#####'

It adds the character passed, in front and back of the string 's', only if length of string 's' is less than the number passed. Here length of string 's' is 41. So, it added '#' at the beginning and end of the string to make the length as 50. It is only for that particular output. No changes is made to the actual string 's'.

Expand Tab

The expandtabs() method will expand tab notations \t into spaces. For this example we will NOT use the string 's', but a new string with a tab in it represented by \t
'Hello\tWorld'.expandtabs()
Output:

'Hello    World'

Without .expandtabs() the output is 'Hello\tWorld'.

Check Methods

Is Alphabet  or Number | .isalnum()

s.isalnum()
Output:

False

.isalnum() returns True or False. If all characters in the string are either alphabet or string, it will return True, else it will return False. The example string also included comma, full-stop, exclamation mark, and space. Thus, it returned False.

Is Alphabet | .isalpha()

s.isalpha()
Output:

False

.isalpha() returns True or False. If all characters in the string are alphabet, it will return True, else it will return False. The example string also included exclamation mark, full-stop, space, and question mark, and numbers. Thus, it returned False.

Is Lower case | .islower()

s.islower()
Output:

False

.islower() returns True or False. If all letters in the string are in lower-case, it will return True, else it will return False. The example string includes some upper case letters, thus it returned False.

Is Space | .isspace()

s.isspace()
Output:

False

.isspace() returns True or False. If all characters in the string are white-spaces, it will return True, else it will return False. The example string includes many non-white-space characters, thus it returned False.

Is Title-case | .istitle()

s.istitle()
Output:

False

.istitle() returns True or False. If all lower-cased words begin with an upper-case character, it will return True, else it will return False. The example string includes many words not beginning with upper-case character, thus it returned False.

Is Upper case | .isupper()

s.isupper()
Output:

False

.isupper() returns True or False. If all letters in the string are in upper-case, it will return True, else it will return False. The example string includes some lower case letters, thus it returned False.

Ends WIth | .endswith()

s.endswith('World.')
Output:

True

.endswith() returns True or False. If the string s ends with the string passed to the function as it is, it will return True, else it will return False. The example string ends with 'World.', thus it returned True. Even the case of all letters must match. If you pass 'world.', it will return false as 'W' is in upper-case in the string s.

Built-in Regualr Expressions

Split | .split()

s.split('or')
Output:

['hello! 1st W', 'ld, 2nd W', 'ld, and 3rd W', 'ld.']

.split() returns a list of parts of the string broken at the string passed, and excluding the string passed. The example string is broken down into parts everywhere an 'or' is encountered and returned in the form of the list. Note that 'or' is excluded in the list.

Partition | .partition()

s.partition('or')
Output:

('hello! 1st W', 'or', 'ld, 2nd World, and 3rd World.')

.partition() returns a tuple of 3 parts. The string is broken down on the first occurrence of the string passed, and three parts are formed - first is the part before the passed string, second is the part of the passed string, and third is the part after the passed string. If the passed string is not encountered in the string, even then it passes a tuple, with first part being the entire string, while second and third part being blank.

Comments

Popular posts from this blog

Difference between .exec() and .execPopulate() in Mongoose?

Here I answer what is the difference between .exec() and .execPopulate() in Mongoose? .exec() is used with a query while .execPopulate() is used with a document Syntax for .exec() is as follows: Model.query() . populate ( 'field' ) . exec () // returns promise . then ( function ( document ) { console . log ( document ); }); Syntax for .execPopulate() is as follows: fetchedDocument . populate ( 'field' ) . execPopulate () // returns promise . then ( function ( document ) { console . log ( document ); }); When working with individual document use .execPopulate(), for model query use .exec(). Both returns a promise. One can do without .exec() or .execPopulate() but then has to pass a callback in populate.

Python - List - Append, Count, Extend, Index, Insert, Pop, Remove, Reverse, Sort

🐍 Advance List List is widely used and it's functionalities are heavily useful. Append Adds one element at the end of the list. Syntax list1.append(value) Input l1 = [1, 2, 3] l1.append(4) l1 Output [1, 2, 3, 4] append can be used to add any datatype in a list. It can even add list inside list. Caution: Append does not return anything. It just appends the list. Count .count(value) counts the number of occurrences of an element in the list. Syntax list1.count(value) Input l1 = [1, 2, 3, 4, 3] l1.count(3) Output 2 It returns 0 if the value is not found in the list. Extend .count(value) counts the number of occurrences of an element in the list. Syntax list1.extend(list) Input l1 = [1, 2, 3] l1.extend([4, 5]) Output [1, 2, 3, 4, 5] If we use append, entire list will be added to the first list like one element. Extend, i nstead of considering a list as one element, it joins the two lists one after other. Append works in the following way. Input l1 = [1, 2, 3] l1.append([4, 5]) Output...

Machine Learning — Supervised, Unsupervised, and Reinforcement — Explanation with Example

🤖 Let's take an example of machine learning and see how it can be performed in three different ways — Supervised, Unsupervised, and Reinforcement. We want a program to be able to identify apple in pictures Supervised Learning You will create or use a model that takes a set of pictures of apple and it analyses the commonality in those pictures. Now when you show a new picture to the program, it will identify whether it has an apple or not. It can also provide details on how confident is the program about it. Unsupervised Learning In this method, you create or use a model that goes through some images and tries to group them as per the commonalities it observes such as color, shape, size, partern, etc. And now you can go through the groups and inform the program what to call them. So, you can inform the program about the group that is apple mostly. Next time you show a picture, it can tell if an apple is there or not. Reinforcement Learning Here the model you create or...