Strings in python – Part 1

Hello Techies!!!

What are strings?

Anything from a letter to a word to a sentence to a paragraph is referred to as string.
For a letter, we will further refer it to as a character (usually called in programming reference).

String Literals are usually surrounded by single (‘hello’) or double quotation marks (“hello”) in python.

a = ‘c’

This means a character c is assigned to a variable named a.

let a variable be named as name,

name = ‘Piyush’

Now string Piyush is assigned to variable ‘name’.

There are many in-built functions you can use to manipulate or use strings in python.

String Manipulation :

First, let’s see how we can print string on command line.

first_name = ‘Piyush’

last_name = ‘Agarwal’

To print them together, we can write print(first_name+last_name)

To add a space between them and make it look better, we can write
print(first_name+’ ‘+last_name)

print strings

Now, we can do different type of operations on string. An operation you just saw above is called concatenation of strings.

We can get length of strings, get characters at different indexes or positions, print part of the strings, split a string, etc.

For finding length of a string, you can use len( pass any string ) function. you just need to pass a string argument into the function and get the length of passed string as result.

In programming languages, positions or indexes start at 0.
For example, In a string first_name= ‘Piyush’, character P lies at index 0, i lies at index 1 and so on.
So, to get a character at specific index, you just have to write first_name[0], which will return you ‘P’. We only need to pass the index of a string in square bracket and get the character in return.
There is a limitation to getting a character, If there is no index possible for a string, the program will throw an error ” IndexError : string index out of range”

We can also specify negative indexes to get characters from end. In above example, if we write first_name[-1] will return h.

string manipulation - part 1

That’s it for today!!

We will continue learning more about strings in next part.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.