Monday, December 11, 2017

Strings in Python

We use string to represent text.by default it's Unicode text in Python 3 but ASCII text in Python 2.And this is one of  the big advantage in Python 3 by the way.Strings can be defined like below:

eg:

'hello world' == "Hello World" == " " "Hello World " " "

There is absolutely no difference which one you use.you can write multi-line string using 3 double quotes but this string  is not going to assign to any variable.it just to be sitting there as a comment.your editor will recognize it.it is a comment.Definning String is very simple just type a variable name and assign it a textual value  and done.
String in Python supports lot of utility methods.some of them are:

eg:

"hello" .capitalize() == "Hello"
"hello".replace("e" , "a") == "hallo"
"hello" .isalpha() == True
"123".isdigit() == true # Usefully when converting to int

"some ,CSV,values" .split(",") == ["Some" , "CSV" , "Values"]

String Format Function-

normally, use when you want to replace existing text in a given string with a variable value.

For example:

name = "pyhthonBO"
machine = "HAL"

Let's print it like this:

"Nice to meet you {0}.I am {1}".formate(name,machine)

So you must be thinking it of bit weird.So let me tell you here {0} and {1} meaning.
{0} represents the variable name argument position in format function.
you can add many argument to the formate function.
python 3.6 introduces string interpolation though So now you can do some thing like

f"Nice to meet you{name}.I am {machine}"

you can also pre-fix with r and u before the string.to deal with raw and Unicode text.its up to you.what you choose.
There are many other string properties like slicing and cutting etc.

No comments: