Essential Takeaways from Python LC-01

2 min read
# stings in python : textual datatype
# ways to create a string :
s1='hello'
s2="your's"
s3="""hy this is a multiline string,
i.e it is written on more than one line."""
print(s1)
print(s2)
print(s3)
# accessing elements in a string :
# single element: using index (which starts from 0)
print(s1[0].upper())
# a stirng of characters: using slicing
print(s3[0:10]) #the starting index is inclusive but the end index is not so it give 0 to 9 indexed characters.
# string functions :
# str.split()-->used for string to list
print(s3.split()) #by default removes extra spaces and splits on whitespaces
print(s3.split(','))#splits by the ',' character.
print(s3.splitlines())#splits by the newline character.
s4=s3.split()
# str.join(iterable) *iterable like list, tuple , etc.* used for iterable to string
print(' '.join(s4))
# str.strip()--> used ot remove all leading and trailing whitespaces or specific characters
s5='abacxyz'
print(s5.strip('az')) #-->it removed all the leading/trailing a&z and returns baxcy.
# str.replace(old, new, count=-1)
print(s5.replace('a','3',-1)) #-->can also leave the -1 part and will work the same.
# str.find(sub) vs str.index(sub)
# Both return the index of the first occurrence of sub.
# Tricky part:
# find() returns -1 if not found
# index() raises a ValueError if not found
# Does: Pads string with zeros on the left to fill the width.
# Tricky if you expect it to pad spaces or to the right.
print('.32'.zfill(4))
# str.partition(sep)--> splits the string into a 3 tuple : (before,sep,after)
print("hello=123".partition('='))
# str.format()-->used for concatination and is better than using +.
print("hello my name is {} and my age is {}".format('bhavesh','19'))
# str.encode()--> converts string into bytes using given encoding
print('hello'.encode())
0
Subscribe to my newsletter
Read articles from Bhavesh Kapil directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Bhavesh Kapil
Bhavesh Kapil
I'm a BTech CSE undergrad from a tier 3 college, documenting my journey from academic setbacks to building real-world skills in coding, ML, and finance. This blog is for anyone who believes in second chances and self-made success. I'm going to document everything I learn here and help you all connect with me by being real and also sharing the mistakes I made along the way, so you don't repeat the same. Let’s go on a journey of self-improvement and see how consistency and the mindset of showing up every day help beat the odds.