Python String (part II)

 Hi there,

Today we going to start part 2 of the python strings lesson, if you did not read part 1, here is the link 

:String part I

In part II, we going to discuss Slicing string, Modifying string, and String concatenation.

okay, let's jump to the lesson.


Slicing String

what is slicing string?

create a substring, that substring is essentially a string, that part of another string

a =" my name is KaviB"
a  is a string.
b="KaviB"
b is also a string as well as a substring of a.

Slice in between the specific range

get characters from index 2 to index 6 (index 6 is not included but index 2 is included)

txt = "I am KaviB"
print(txt[2:6])



Slice from the start

txt = "I am KaviB"
print(txt[:6])



Slice to the end

txt = "I am KaviB"
print(txt[2:])



Slice using negative indexing

negative indexes use to start from the end.

I am KaviB

B=0
i=-1
v=-2
a=-3
so on...

txt = "I am KaviB"
print(txt[-7:-1])






Modify String


Upper Case

you can use the upper() function to change characters to uppercase.

you can use the lower() function to change characters to lowercase.

txt = "I am KaviB"
print(txt.upper())
print(txt.lower())



Replace String

you can use the replace() function to replace characters.

txt = "I am KaviB"
print(txt.replace("K","N")) //K will be replaced by N



Split Strings

you can use the split() function to divide the string into substrings using the seperator.

txt = "Hi there, I am KaviB"
print(txt.split(","))



lstrip() and rstirp()

you can use the lstrip() function to return left trim version and use rstrip() to return righty trim version.

//if you don't pass any argument, lstrp() removes left side spaces and rstrip() removes right side spaces
txt = "        I am KaviB    "
print(txt.lstrip())
print(txt.rstrip())




//if you pass charactors as arguments , lstrip() removes those charactors from left side and rstrip() removes those charactors from right side
txt = "    wewe    I am KaviB   wewe "
print(txt.lstrip(" we"))
print(txt.rstrip(" we"))





Use this link to refer to more string methods click here


Concatenate String

In python, we can concatenate strings using the + operator.

a="hello"
b="world"

print(a+b)
print(a+" "+b)






...................................................................End..............................................................................

See you soon with String part III
follow me
Thank you
KaviB

Comments

Popular posts from this blog

Review about Dell Laptops

Digital clock using python tkinter

Python String (part I)