We all learnt what are the python strings. Like concatenation, repeating one strings in multiple times. Hope that blog has impressed you. If you want to look at the blog Previous.
Today's related to strings and but a step forward to the before blog. That is placeholders .
Context
- Indexing
- Slicing
- Placeholders
Indexing
It is one of the operation in string. It is also a numbering given to letter in words in sentence. It is useful to access the characters in the string individually.
Sen = "charan loves apples" # declaring a str
Indexing of a strung takes places like this
c h a r a n l o v e s a p p l e s .
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
0 1 3 4 5 6 7 8 9 ..............
Even the space holds a index too .
This is how the indexing pattern.
If you comes in reverse (from last ) of the sentence.
c h a r a n l o v e s a p p l e s
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
-6 -5 -4 -3 -2 -1
This is the theory.
Program
sen = "charan loves apples"
sen[0] #accessing the first letter
Sen[4] # accessing the fifth letter
This is how we do the indexing in the python.
Slicing
In indexing, we can only access one character.That makes slicing come into picture to access a word in string or a part of a word.
Syntax:
Var[SI : EI]
Where :
Var = string variable.
SI = Starting Index
LI = Ending Index
Here , EI is omitted.see the example you will get the clarification.
sen = "charan loves apples"
# let's try to get one word i.e, "charan".
sen[0:6] # here sixth index is holded by space
sen[0:5]
Let's try to do it in program.
In the above pic you can see the ending index is not taken to count.
Let us move on to next topic
Placeholders
Why we have to use placeholders . If we want to use sentence (or) a string for different bames or number.
Let's take a example
Same sentence that is
sen = "charan loves apples. If other friends like same apples too.
Gokul and vignesh even likes the apples .
We can't write
"Gokul loves apples"
"Vignesh loves ..... "
And another friend that is why we use placeholders.
We use some substitutes for each data types.
In above example, we are only changing the name of a person rest of thr lle string is same. So, we have to use substitutes for only person name .
Substitutes for all data types :
String -> %s
Integer -> %d
Float. -> %f
Double -> %lf
Characters -> %c
Let's see application of concept
sen = "%s loves apples"
sen%("charan") # substituting word with %s
sen%("vignesh")
Now ,we will see double variable placeholders . Substituting two variables.
Eg
sent = "%s%s loves apples"
sent%("charan","vignesh")
If you want to get the gap between names. Maintain gap between substitutes.
Let's see combination of stting and integer.
app = "%s is %d years old :
app%("Irfaan",18)
Comments
Post a Comment