Search Here

Strings in python

Hello, how are you guys!!! I hope you will be fine and also enjoying this tutorial. In my previous post you learned about  numbers in python in very detailed example. We learned that there are two types of numbers in python. First is "int" and the second one is "float".


We also learned that how to convert "int" into "float" and vice verse. Today you will learn about "strings" in python with example.

Python Strings
        Python has some very powerful facilities for working with strings. And in fact, in Python 3, they become refined, and in some cases even more powerful. Let's get right into strings, and we will start by defining a String (line no ). I will just call it s, and I will say 'This is a string!' (line no 2) and we will go ahead, and we will print(s). And there we have the string.

1. s = 'This is a string'
2. print(s)

Strings in python

Strings in Python are immutable objects, and they're created with either single quotes or double quotes. And so if we change those single quotes to double quotes, we will see that we get exactly the same result.

Python escape character / new line

        You can use Escape characters in a string, as you can in many languages. So if I put in (line no 1) a \n, for example "s = 'This is a\n string.' that will introduce a new line in the middle of the string. And we will print(s), we see that there is a new line now between the a and the s of string. 

1. s = 'This is a\n string'
2. print(s)

Strings in python 

 On the other hand, if I want this \n to actually be a part of the string, rather than getting replaced with a new line, I can put the letter r before the definition of the string like that (s = r"This is a\n string."), and if I print(s), I get the \n as part of the string. This is called a raw string, and the place where this gets used the most is when creating regular expressions. And we will get into regular expressions in some detail in another post. The code snippet of above description is given below:

1. s = r'This is a\n string'
2. print(s)

Strings in python 

In addition to these sorts of Escapes with the backslashes, you can also do some formatting and replacing of variables in the string (between the string). For example, if I create a number and call this, say "num", and give it a value of 10, I want to put that 10 right in the middle of the string. There are two different ways to do this. The first one is by using the python 3 way and the second is python 2. Firstly I am going to show you the Python 3 way to do this.

 #!/usr/bin/python3
def main():
    num = 10
    s = "This is a {} string".format(num)
    print(s)      
if __name__ == "__main__": main()

Output: This is a 10 string

Strings in python

Description of above code:
 
This actually inserts the value of "num" in the middle of the string. We have these curly braces here, and those get replaced with the format. So format is a method of the string object. And so this literal string is actually an object. Remember, everything in Python is an object. We can use this objecty-referencing operator, this period, to access a method of that object, and do this variable replacement. So this is very powerful, and this is very common. And you will see it done this way in new Python 3 code.

And we will look briefly at the Python 2 way to do it as well, because you will see that a lot. For all your new code, you want to use the Python 3 way, which is with the format method of the string object, because the Python 2 way is going to go away. It's considered obsolescent, and it will be dropped in the next version of Python. 

#!/usr/bin/python3
def main():
    num = 10
    s = "This is a %s string" % num
    print(s)       
if __name__ == "__main__": main()

Strings in python 

 Description of above code:

In Python 2 code, you'll see it's done this other way. I am going to put %s here, and over here a % sign and the letter num. And print(s). You see we get the same result. This is the way that it was done in Python 2. And this is a bit of a hack. It's perfectly valid, and you will see it a lot. You will even see it some in Python 3 code that's written by people who are used to Python 2, and that's fine. The reason you don't want to use this construct is because it is considered obsolescent, and it will be dropped in the next version of Python. So you'll see this, you want to know what it does, but the right way to do it in Python 3 is to use the new format method of the string object.
Accessing values in strings

To access sub string we use square brackets [ ] along with index or indices. For example
>>> s = 'London'
>>>
print(s[0])
>>> print(s[1:5])

When we run the above code it will produce following result.
Output: L
Output: on

Strings in python 

How to concatenation two strings:

The concatenation of strings in python is very simple and easy. For example if we have two strings s1 and s2, and the value of  the first one is "Hello" and the another is "World". And we want to concatenate it we use "+" operator to do this. Code below shows how to concatenate the above strings.

>>> s1 = 'Hello'
>>> s2 = 'World'
>>> print(s1 + s2)

Output: HelloWorld

Strings in python 

Python Triple Quotes

There's one more way I want to show you for defining a string, and this is using the triple quotes. And you can triple either the single quotes or the double quotes. So I can either do it this way (s = '''This is a string'''), or instead of these triple quotes, I can do it this way with the double quotes, like this (s = """This is a string"""). And you'll see it's done both ways. I tend to use the singles tripled instead of the doubles tripled. Now what this does is it allows you to have a string that spans several lines.I will explain what this does in a moment.  For example

#!/usr/bin/python3
def main():
    s = '''\
    This is a string
    this is another line of string
    and one more line of string'''
    print(s)       
if __name__ == "__main__": main()

Output: 
    This is a string
    this is another line of string
    and one more line of string

Strings in python 

Description of above code:
 
What I will often do is I will start with a backslash and a new line and go all the way back to the end of the line like that, and this will allow me to just have line after line of text and more text, and to have it actually started at the beginning of it. This is useful if you have lines and lines and lines of text. And so the way you do this is with three quotes, either single quotes or double quotes, at the beginning and the end. And the result will be a string that has the new lines, and it's all formatted exactly like you type it in. What this here does, this backslash and a new line, is that it escapes the new line, so that it doesn't actually show up in the string.

 Unicode strings:

In python normal strings are stored as 8-bit ASCII, while unicode characters and strings are stored as 16-bit Unicode. Unicode string uses the prefix 'u'. For example.

>>> print(u'Hello, Python')

Built-in String Methods:

Python allows us to modify strings in very easy way. There are several buitl-in string methods in python, but here we discuss upper(), lower(), count(), find() and replace() .

upper() and lower():
As the name shows performing the upper() method on strings convert all of the character to uppercase whereas lower() method of string converts all of the character of the string to lowercase. For example if we have a string s1 = 'convert to uppercase' and s2 = 'CONVRT TO LOWERCASE'. Then the magic of python string built-in method / function is given below:

#!/usr/bin/python3
def main():
    s1 = 'convert to uppercase'   
    print(s1.upper())
    s2 = 'CONVERT TO UPPERCASE'
    print(s2.lower())      
if __name__ == "__main__": main()

Output:
CONVERT TO UPPERCASE
convert to uppercase 

Strings in python

count():
Count method count the number of times a character or sequence of character appears in a string. For example if we have a string ( s = "this is a string and this is not a string") and we want to count the occurrence of "t" in the above string, we use python count() method.
#!/usr/bin/python3
def main():
    s = "This is a string and this is not a string"
    print(s.count('t'))     
if __name__ == "__main__": main()

Output:
4

find():
We can find / search a specific character or characters in a string by using python built-in find() method. The syntax for finding a string is given below:
str.find(str, beg=0 end=len(string))

Code description:
str :  string to be searched.
beg: starting index, by default its value is 0.
end: ending index, by default its equal to the length of the string.

Example:
>>> s1 = 'this is a string'
>>> s2 = 'str'
>>> print(s1.find(s2))
10
>>> print(s1.find(s2, 10))
10

Strings in python 

Today you will learn about strings in python in very detail. You also learned string manipulation and python built-in function for strings.

Post a Comment

0 Comments