Skip to main content

Python crash course: Strings

Strings!



Strings are a major part of any programming language, they are used for textual data. In many basic programming languages there isn’t a specific data type, so programmers need to make character arrays to fulfil most of their string requirements. But luckily python has a string type which takes care of strings like names, sentences, other textual data. The string type is a sequence of characters, meaning if you store “Ankush” it will interpret it as “A”, “n”, “k”, “u”, “s”, “h”, that means we can access any element of the string by its index.

This idea of a sequence is an important one in Python and we will touch upon it later on in the future.

In this article will cover following topics:

  • Creating Strings

  • Printing Strings

  • String Indexing and Slicing

  • String Properties

  • String Methods

  • Print Formatting

Creating a String

To create a string in python you need to write our sequence of characters in single quotes or double quotes.

In [1]:

# Single word

'hello'

Out[1]:

'hello'


In [2]:

# Entire phrase 

'Hello! you are welcome'

Out[2]:

'Hello! you are welcome'


In [3]:

# We can also use double quote

"Hello! you are welcome"

Out[3]:

'Hello! you are welcome'


In [4]:

# Be careful with quotes!

' I'm Iron man, this string will generate error'


  File "<ipython-input-4-293da7b7105b>", line 2

    ' I'm Iron man, this string will generate error'

        ^

SyntaxError: invalid syntax


In case you are writing a string which already contains a single quote then use double quotes to store that string instead. The reason for the error in the above cell is because the single quote in (I'm) in the string. You can use combinations of double and single quotes to get the complete statement.


In [5]:

"Now I'm ready to use the single quotes inside a string!"

Out[5]:

"Now I'm ready to use the single quotes inside a string!"


Printing a String

Jupyter notebook automatically prints the element (variable/output) which is present in the last line of the cell but the correct way of printing a string in python is, by using print() method.

The way the print method is used is shown below.


In [6]:

# We can simply type a string in quotes

'Hello World'

Out[6]:

'Hello World'


In [8]:

# But we can only print the last line of the block

'Hello! World attempt one'

'Hello! World attempt two'

Out[8]:

'Hello! World attempt two'

Now let's use the print() method to print strings.


In [12]:

print('Hello World attempt one')

print('Hello World attempt two')

print('Use \\n to print a new line like below code')

print('Line one \nline two')

Hello World attempt one

Hello World attempt two

Use \n to print a new line like below code

Line one 

line two

Basics of strings

we can use len() method if we want to print the length of a str. The property of a len function is that it counts every character including spaces punctuations.


In [13]:

len('Hello World!')

Out[13]:

12

String Indexing

As I have mentioned earlier that strings are basically a sequence of characters in Python so we can access the characters of a string using indexing. To use indexing in Python strings we can use [ ]. We can put brackets after the strings or the variable which containing string and put the index number which we want to access in the bracket. The indexing in Python strings starts with 0 and we can access the last element of a string by using -1 index.


In [14]:

# Assigning a string to a variable

s = 'Hello World!'


In [15]:

#Check the variable

s

Out[15]:

'Hello World!'


In [16]:

# Print the object

print(s) 

Hello World!

Now let's practice some indexing


In [17]:

# Accessing the first element of the string(the first character)

s[0]

Out[17]:

'H'


In [18]:

s[1]

Out[18]:

'e'


In [19]:

s[2]

Out[19]:

'l'


To perform slicing in Python strings we use : to separate the starting and end indexes. we put the starting index before and the last index after the :.

To get everything from the first element to the last element we can use the following syntax


In [21]:

s[1:]

Out[21]:

'ello World!'


In [22]:

# Note that there is no change to the original s

s

Out[22]:

'Hello World!'


In [23]:

# To get every thing from start to the 4th index

s[:4]

Out[23]:

'Hell'


In the previous block, we are telling python to get the string from the index 0 to the Index 4 but it does not include the element at index 4, this trend of indexing can be noticed all over the Python where the last element is not included during indexing. You will encounter this a lot of times throughout the course.


In [25]:

#Get the whole string

s[:]

Out[25]:

'Hello World!'


We can also use negative indexing to traverse the string from back

In [26]:

# Last letter

s[-1]

Out[26]:

'!'


In [27]:

# Get everything except the last element

s[:-1]

Out[27]:

'Hello World'


We can also specify the step size during slicing, for this we have to place another column and after that [] we place the step size.

For example, if we have to slice the string the but only include the alternate characters then we use the step size of two.


In [28]:

# Get everything,with a steps size of 1

s[::1]

Out[28]:

'Hello World!'


In [30]:

# Get everything,with a steps size of 2

s[::2]

Out[30]:

'HloWrd'


In [31]:

# we can use this trick to print the string backwards

s[::-1]

Out[31]:

'!dlroW olleH'

String Properties

Now let's see some spring properties, the first and very important property is immutability, that means after the definition of the string we cannot alter a single character of the string by assigning another character to its index. we use indexing to get a particular character of a particular index but we cannot use indexing to change a character at a particular index.

For example:

In [32]:

s

Out[32]:

'Hello World!'


In [33]:

# Let's try to change the first letter to 'x'

s[0] = 'x'


---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-33-976942677f11> in <module>

      1 # Let's try to change the first letter to 'x'

----> 2 s[0] = 'x'


TypeError: 'str' object does not support item assignment


In the cell above we tried to assign an item to the string but we can see that error clearly says that strings do not support item assignment.

We use + sign to concatenate two strings together


In [34]:

s

Out[34]:

'Hello World!'


In [35]:

# Concatenation of two strings

s + ' concatenate me!'

Out[35]:

'Hello World! concatenate me!'


In [36]:

# Reassigning to the variable the concatenated string

s = s + ' concatenate me!'


In [37]:

print(s)

Hello World! concatenate me!


It's really fun to work with Python here's an example we can actually create repetitions in a string in Python by using * sign


In [38]:

letter = 'z'


In [39]:

letter*10

Out[39]:

'zzzzzzzzzz'

Basic Built-in String methods

Now let’s see some very common inbuilt methods of string which we will be using frequently throughout the course. These methods are functions inside the object that can perform actions or commands on the object itself.You will also use these methods very frequently when you be coding.

To call any method in Python we use the following format:

object.method(parameters) Where parameters represent the extra arguments we pass in the method.

Here are some examples of built-in methods in strings:


In [40]:

s

Out[40]:

'Hello World! concatenate me!'


In [43]:

# Upper Case

s.upper()

Out[43]:

'HELLO WORLD! CONCATENATE ME!'


In [44]:

# Lower case

s.lower()

Out[44]:

'hello world! concatenate me!'


In [45]:

# Split a string by blank space

s.split()

Out[45]:

['Hello', 'World!', 'concatenate', 'me!']


In [46]:

# But you can also pass a space in the split method if you want.

s.split(' ')

Out[46]:

['Hello', 'World!', 'concatenate', 'me!']


In [47]:

# Split by a specific element excluding that element

s.split('W')

Out[47]:

['Hello ', 'orld! concatenate me!']


The string object has a lot of inbuilt methods, we are not exploring all of them but you will be exploring them as you code more and more in python.

In the next article we will be covering the "list" object.

Till then good luck!

Comments

  1. This is very much useful. Every new python programmer need to see this blog.
    I just loved it

    ReplyDelete

Post a Comment

RUNTIME