strings and string methods
strings and string methods
S = “Python”
Positive 0 1 2 3 4 5
Indexing
P y t h o n
Negative -6 -5 -4 -3 -2 -1
Indexing
>>> s = “Python”
>>>s[0]
‘P’
>>>s[1]
‘y’
>>>s[-1]
‘n’
>>>s[-4]
‘t’
3. slicing
Slicing help us to get substring.
String Replication
A string can be replicated using * operator
>>> ‘Alice’ * 3
‘AliceAliceAlice’
5. String Traversing
Visiting every character in a string using a for loop is called string traversing
Examples 1:
for i in “PYTHON”:
print(i)
OUTPUT:
P
Y
T
H
O
N
Examples 2:
S = “PYTHON”
for i in range(len(S)):
print(S[i])
OUTPUT:
P
Y
T
H
O
N
6. String Methods
upper() upper() method returns the string in upper case letters
“GOOD MORNING”
lower() lower() method returns the string in lower case letters
>>> s = “Good Morning”
>>> s.lower()
“good moring”
join() join() method takes list of strings as argument that need to be joined
together into a single string value.
partition() The partition() string method can split a string into the text before and
after a separator string.
>>> ‘coding is fun’.partition('is')
('coding ', 'is', 'fun')
rjust() The rjust() and ljust() string methods return a padded version of the string
they are called on, with spaces inserted to justify the text
ljust()
>>>'Hello'.rjust(10)
center() ' Hello'
>>>'Hello'.ljust(10)
'Hello '
>>>’Hello’.center(10)
>>>'Hello'.ljust(10,’*’)
'Hello*****'
>>>’Hello’.center(10, ‘*’)
'**Hello***'
strip() • The strip() string method will return a new string without any
whitespace characters at the beginning or end.
lstrip() • The lstrip() and rstrip() methods will remove whitespace characters
from the left and right ends, respectively.
rstrip()
>>> spam = ' Hello, World '
>>> spam.strip()
'Hello, World'
>>> spam.lstrip()
'Hello, World '
>>> spam.rstrip()
' Hello, World'
islower() returns a Boolean True value if the string has at least one letter
and all the letters are lowercase. Otherwise, returns False
isupper() returns a Boolean True value if the string has at least one letter
and all the letters are uppercase. Otherwise, returns False
>>> 'HELLO'.isupper()
True
s = input(“Enter a string:”)
if s == s[: : -1] :
print(“String is a palindrome”)
else:
print(“String is not a palindrome”
9. Using string slicing operation write python program to reverse each word in a given string (eg:
input: “hello how are you”, output: “olleh woh era uoy”)