Strings in Python¶
- '', "", and escape characters
- Multiple strings with triple quotes
- immutable
- upper() and lower()
- isuuper(), islower()
- isalpha(), isalnum(), isspace(), isdecimal(), istitle()
- startswith(), endswith()
- join(), split()
- ljust(), rjust(), center() => justifying texts
- strip(), rstrip(), lstrip()
- replace()
- string formatting
'', "", and escape characters¶
In [5]:
print('hello world')
print("hello world")
print('hello\'world')
print('hello\nworld')
print('hello\tworld')
print('''hi
hi
hi''')
upper() and lower()¶
In [8]:
s = "hello world"
print(s.upper())
print(s) #immutable
s = s.upper()
print("upper",s)
print(s.lower())
isupper() and islower()¶
In [7]:
s = "hello world"
print(s.islower())
print(s.isupper())
isalpha(), isalnum(), isspace(), isdecimal(), istitle()¶
In [15]:
print("hello".isalpha()) #True
print("hello123".isalpha()) #False
print("hi123".isalnum()) #True (both alpha and number)
print("Hello world"[5].isspace()) # True ("5th pos is space")
print("12334".isdecimal()) #True
print("Hello My Name Is Arun".istitle()) #True (Every word starts in upper case)
startswith(), endswith()¶
In [16]:
h = "hello world"
print(h.startswith("hel"))
print(h.endswith("rld"))
join() , split()¶
join function is used to join a list of strings with a particular string.split function is used to split a string based on a particular string value.
In [17]:
route = ["kanyakumari","chennai","bangalore","goa","mumbai","delhi","kashmir"]
print("-".join(route))
In [18]:
route = "kanyakumari-chennai-bangalore-goa-mumbai-delhi-kashmir"
places = route.split("-")
print(places)
ljust(), rjust(), center()¶
These functions are used to justify the string values
In [20]:
s = "hello"
print(s.ljust(10))
print(s.ljust(10,"*"))
print(s.rjust(10))
print(s.rjust(10,"*"))
print(s.center(10))
print(s.center(10,"*"))
strip(), rstrip(), lstrip()¶
In [29]:
s = " hello "
print(s)
print(len(s))
print(s.strip())
print(len(s.strip()))
print(s.rstrip())
print(len(s.rstrip()))
print(s.lstrip())
print(len(s.lstrip()))
replace()¶
In [30]:
s = "hi my name is arun"
s = s.replace("arun","prakash")
print(s)
string formatting¶
In [38]:
name = "arun"
place = "chennai"
age = 24
print("Hi, my name is %s, and I'm from %s. I'm %d" %(name,place,age))
print("Hi, my name is {name}, and I'm from {place}. I'm {age} ".format(name = name,place = place, age = age))
No comments :
Post a Comment