Monday, 17 June 2019

Strings in Python

Introduction

In this quick article we'll be talking about strings in Python. Strings are a common data type found in most programming languages. The most basic definition of a string is a sequence of characters that can store anything.
For example 'hello world' is a string. If we type it in the Python REPL, it will print the string back.

>>> 'hello world'
'hello world'
>>>

To assign a string to a variable, type: variable='string' and then print the value of the variable using the print function. For example, on the REPL

>>> greeting='Good Morning'
>>> print greeting
Good Morning
>>>

Concatenating strings:
We often need to concatenate strings in our everyday scripts. To concatenate two strings we use the plus (+) operator. Here is an example.

>>> first_word='hello'
>>> second_word='world'
>>> print (first_word+' '+second_word)
hello world
>>>

Converting a number to a string:
To convert a number to a string we use the str() function. Here is an example.

>>> year=1990
>>> print ('I was born in'+' '+str(year))
I was born in 1990
>>>

If you do not perform the conversion you get a type error.

>>> print ('I was born in'+' '+year)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects


String methods:
Python is an object oriented language and a string in Python is a type of object. An object encapsulates some sort of state. In case of a string the state is a sequence of characters. We can call methods on strings since they are objects. Methods contain functions. Here are two methods that you can use on string objects:

1. Find method:
This searches of a character/s in a string and returns the index value where the character was found in the string.

>>> name="sahil"
>>> name.find("il")
3

2. Lower method:
This converts all characters in a string to lower case.

>>> name="sAhIl"
>>> name.lower()
'sahil'


Slicing strings:
Extracting a part of a string or slicing it is something that Python excels at. To slice a string we need to specify tell Python the starting and ending indices where the string needs to be sliced at. These indices need to be enclosed within square brackets and separated by a colon(:) symbol. We can also assign the sliced strings to variables. Here are a few examples:

>>> name='sahil suri'
>>> fname=name[0:5]
>>> fname
'sahil'
>>> lname=name[6:]
>>> lname
'suri'
>>>


Conclusion:

This concludes our discussion on strings in Python. I hope that you found this post to be useful and there are more Python tutorials on the way.
Here are a few examples.

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...