Strings in Python

In this Python at RabinsXP, we are going to learn everything about the strings such creating, printing, indexing, and slicing, etc. We also learn about its properties, methods, and formatting.

What are Strings?

In Python, Strings are used for storing the text information such as a name which actually is treated in a ‘sequence. This means every element in the string can be track backed by Python.

For example, if we provide a string as “Hello World”. Then it is stored in the sequence of the letter in a specific order. i.e using index we can get the particular letter from the “Hello World” in the sense that if we grab index[4], it will give us the letter ‘o’ which is at the fifth position (or 4th index).

Here we are going to learn about the followings:

  1. Creating Strings
  2. Printing Strings
  3. String Indexing and Slicing
  4. String Properties
  5. String Methods
  6. Print Formatting
python-strings

Strings in Python // RabinsXP

Creating a String

In Python, we use “double quotes” to represent a string. ‘Single quotes’ can also be used,

  • Single-word e.g. ‘hello’
  • Entire phrase e.g. ‘This is also a string’
  • Double Quotes e.g. “I am wrapped in “double quotes”

Now make sure not to use words like I’m, You’re, He’s,  She’s, etc. You may notice these words already have the symbol ( ). This will lead you an error if you give something like this to the string: ‘Shes is an actress.’ Instead of this, we can simply use both types of quotes like this. “Shes is an actress.”

# Now let’s learn about printing strings!

Printing Strings

We can output the string using REPL (read-eval-print-loop) but a proper way to do is execute or display is using the print function. REPL is a shell interface that reads each line of input, evaluates that line, and then prints the result.

So, we now know to define string using quotes. Now let’s print these string using the print function.
print('I am a string')
print('I will again appear after a new line')
print('\n')
print('I am a string')
print("If there was not the '\n' new line would not have been printed")

String Basics

To find out the length of the string, we use the function len()  Example len('Hello Users') will count the numbers of string character and prints it.

String Indexing and Slicing

As we already know that Python stores string in sequence. We know strings are a sequence, which means Python can use indexes to call the parts of the sequence. Let’s learn how this works.

In Python, we use brackets []  to call any index of the object. As most of the programming languages, Python also starts with zero (0) index.

We will learn this using an example.

First, let’s assign any string say:
a = 'Hello String'

Now we print the object.
print(a)

Indexing

Let’s start indexing it.

a[0] shows the first element (H) assigned to the letter a.

a[1] shows the second element (e) assigned to the letter a.

a[2] shows the third element (l) assigned to the letter a.

a[3] shows the fourth element (l) assigned to the letter a.
and so on…

Slicing

Now using the symbol colon (:) or scope we can grab the parts of the strings. Here grabbing the certain part means ‘slicing’ in terms of Python just like we slice only some piece of an apple to eat (not all).

We knew the length of the string previously using the function len(a). Now, let’s slice the string stored ( i.e ‘Hello World’) in many ways.

a[1:] It grabs from the first index to the last index. i.e Hello World

a[:4] It grabs from the first index to the fourth index. ie. Hell

Note, in python, [:4] means from this up to that, but not including that, means in the above example, from index one, up to index 4, but not the index 4 itself.

a[:]This grabs everything. i.e Hello World

Python also supports negative indexing means we can slice from backward too.
Like if we use a[1], it slices from the first index and if we use a[-1], it slices from the last index.
Let’s look some examples:

Last letter (one index behind 0 so it loops back around)
a[-1] It grabs only the last letter or last index.

# Grab everything but the last letter
a[:-1] It grabs everything from last to first but excluding the last index.

Now making use of both index and slice notation (scope) we can now grab elements in the desired sequence.

Say we can grab specified step size (the default is 1). For instance, we can use two colons in a row and then a number specifying the frequency to grab elements. For example:

a[::1] It grabs everything, but go in steps size of 1.

a[::2] It grabs everything, but go in step sizes of 2.

a[::-1] It grabs everything backward but goes in steps size of 1.

String Properties

Python strings are immutable that means once assigned it can’t be changed or replaced.

As we have assigned a= ‘Hello Strings’ already now if we try to change the word ‘e’ with ‘3’ like below we get an error.

a[1]='3' This gives an error messages stating we can’t change the item assignment.

But we can do Concatenate strings.

Concatenate strings!

Concatenate means joining together in series. Python allows concatenating two or more strings. Or let’s say adding more to the already defined string. We can do like this.

a + 'World'
Before, print(a) outputs ‘Hello String’ but not print(a) displays ‘Hello String World’.

We can concatenate ‘n’ number of times or repeat it using the multiplication symbol (*).

Eg. b = ‘ABC’ and now doing print(b*3) will display three times i.e ABCABCABC

String Methods (Built-in)

Python has some reserved strings method. These built-in methods are the functions inside the object which performs specific actions on the object itself.

In Python, the method names are called using the full stop or periods (.). The basic syntax is:object.method(parameters) The parameters are the arguments we can pass to the method.

Here are the major built-in string methods used in Python.

  1.  s.upper() upper case string.
  2. s.lowe() lower case string
  3. s.split() splits the string by a blank case (default)
  4. split(‘S’) splits the string by specific element (here S) but the element itself is not included.

Print Formatting

In Python, we use the .format() method to add formatted objects to printed string statements. We can insert another string with curly brackets {} and join it with new string format method. Here’s an example of how to do this.

The syntax is: 'My first string is  {var1} then also {var2}'.format(var1='something1',var2='something2')

The few more examples can make you easier to understand.

print('This is a string with an {p}'.format(p='insert'))

print('One: {p}, Two: {p}, Three: {p}'.format(p='Hi!')) for multiple times.

print('Object 1: {a}, Object 2: {b}, Object 3: {c}'.format(a=1,b='two',c=12.3))  for several objects.

Conclusion

We now know who to create, print, index, and slice the string in Python. We also know understand the string properties, built-in methods, and print formatting the strings. This concludes the end of ‘Strings in Python’.

Next, in the Python programming series (Python at RabinsXP), we will learn about Lists in Python.

Rabins Sharma Lamichhane

Rabins Sharma Lamichhane is the owner of RabinsXP who is constantly working for increasing Internet of Things (IoT) in Nepal. He also builds android apps and crafts beautiful websites. He is also working with various social services. The main aim of Lamichhane is to digitally empower the citizens of Nepal and make the world spiritually sound better both in terms of technology and personal development.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

nineteen − 6 =

%d bloggers like this: