Start To Learn Python Right Now EP06: Python Strings Part 02

 


In Episode 05 we started learning Python String basics. This is the second part of it. You can mainly learn about String formatting and Uppercase, Lowercase with some other details about Python Strings in this tutorial. 

Uppercase and Lowercase

   You can convert your string completely to a lowercase or uppercase value using Python upper() or lower() functions.You can do it by very simple code like below,

Uppercase    

 ex: u = "softexs.com"
      print(a.upper())

Lowercase

ex: l = "SOFTEXS.COM"
      print(a.lower())

Let's see it from the Python code editor


Replace, Remove and Split Strings

     In Episode 05 we learned that Python strings work as a list, and we got characters in a string using Python Indexing options. So, we are also able to split, replace. remove string using simple Python commands. Let's see how to do that...
 

Replace

   ex: r = "softexs.com"
         print(r.replace("s", "a"))
  In here the first word we mentioned inside the print statement ("s") is the word we command to replace, and the second character ("a") is the character we replace instead of "s"

Remove Space

   ex: s = "softexs.com"
         print(s.strip())
This command removes spaces in the beginning and end of the strings. 


Split Text

   ex: sp = "softexs.com"
         print(sp.split("t"))
  This command splits string into two words in the character "t"


Formatting Strings

  When you want to put a few variable values in a final text or output formatting is the best option. we are using {} and format() statements to work with fromatting. I'll explain it to you with examples. 
ex: a = "science"
      b = "technology"
      c = "programming"
      d = "softexs.com is a {}, {}, {} teaching and explaining website."
print(d.format(a, b, c))

   formatting using to perform this kind of task, you can change the variable and the final text also change according to the variable. You need to keep in mind that final text indexing is according to the pattern you put variables inside format(). In my case, it is a, b, c. Also, you can define a specific variable in a specific place in the final text. You can do it as below, 
ex :a = "science"
      b = "technology"
      c = "programming"
      d = "softexs.com is a {2}, {1}, {0} teaching and explaining website."
print(d.format(c, b, a))

You'll see I put c, b, a inside format() instead of a, b, c.  but I also put the indexing order I need inside the {} scope in the final text. I put 0 to get the first letter of format(), 1 to get the second letter of format() and 2 to get the second letter of format(). because I mentioned in a previous post that Python values start in 0. 


Post a Comment

If you have any doubt, Let us know

Previous Post Next Post