PYTHON STRING
2nd Part
This is our python string second part. So, Let’s get coding.
You want to search a word from your string. I give you a 1000 text
file. You want to search your favorite word. How you search this.?
Python has a find() method. Let’s give you a couple of examples.
>>> country = “Bangladesh”
>>> country.find(‘Bangla’)
0
find() method return which position you find ‘Bangla’ string.
you find method found ‘Bangla’ in 0 positions. Again, I give
you the scenario.
B a n l a d e s h
0 1 2 3 4 5 6 7 8
so, when you put ‘Bangla’ in find method, it starts position 0.
That’s why it returns zero. Now, if I give ‘abc’, then find method
returns -1.That means find method does not found your ‘abc’ in
‘Bangladesh’.
>>> country.find(‘abc’)
-1
>>> full_name=”iftekharul islam”
>>> full_name
>>> full_name.find(‘tekharul’)
2
why two? I said that it always start the first position. What is
‘t’ index number in full_name. Think again. I know you know the
answer. you are the best. Yeah, ‘t’ index number is 2.
i f t e k h a r u l
0 1 2 3 4 5 6 7 8 9
Now, you can ask me why ‘.find()’. Why you use dot(.)?. Good
question.Here the country is an object. The string is an object.
String object has a many methods. We discuss object later.
replace() method
Now we want to change string inside. Really? How?>>> Boyfriend = “messi”
>>> Boyfriend.replace(‘messi’,’ronaldo’)
'ronaldo'
you can use variable
>>> ex_girl = “shakira”
>>> current_girl=”Laila”
>>> ex_girl.replace(ex_girl,current_girl)
‘Laila’
>>> ex_girl
‘shakira’
Here, ex_girl still same. When I use replace method ex_girl or
Boyfriend example, replace() method make new string and then return
it. But main string ex_girl does not change.
>>> country = ‘Bangladesh’
>>> new_country = country.replace(‘B’,’b’)
>>> new_country
‘bangladesh’
>>> country
‘Bangladesh’
I am finishing here. I will write string last part. So, stay tune
with me. God Bless you.
No comments:
Post a Comment