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
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, 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.
That’s it for today!!
We will continue learning more about strings in next part.