Strings

In Python, strings are among the most widely used types. They are easily made by simply surrounding characters in quotations. Python treats single quotes and double quotes the same way. Assigning a value to a variable and creating a string is really straightforward.

Example:

var1 = ‘Hello World!’

var2 = “Python Programming”

Python doesn’t have a character type; as they are viewed as one-length strings, they are also regarded as substrings.

Use the index or indices to get your substring along with the square brackets for slicing to access substrings.

#!/usr/bin/python

var1 = ‘Hello World!’

var2 = “Python Programming”

print “var1[0]: “, var1[0]

print “var2[1:5]: “, var2[1:5]

The outcome of running the aforementioned code is the following:

var1[0]:  H

var2[1:5]:  ytho

By (re)assigning a variable to another string, you can “update” an already-existing string. The new value may be connected to the old value or to an entirely separate string. For instance,

#!/usr/bin/python

var1 = ‘Hello World!’

print “Updated String :- “, var1[:6] + ‘Python’

The outcome of running the aforementioned code is the following:

updated String :-  Hello Python

Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

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

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in