String methods

In addition to the operations defined for all sequential data types, Python provides string-specific methods, some of which are listed here.

Code Explanation

LineDescription
1Initializes a variable with the value Hello world
4Returns a list of the words in the String Variable
11Returns the index of the specified character (lowest index)
18Returns the index of the specified character (highest index)
22Replaces an existing word in the String with a new one
26Returns a copy of the String converted to lowercase
30Returns a copy of the String converted to uppercase
35Returns a copy of the String with leading and trailing whitespace removed
myString = " Hello world "

# Return a list of the words in the string, using sep as the delimiter string.
myList = myString.split()
print(myList)

# S.find(sub[, start[, end]]) -> int
# Return the lowest index in S where substring sub is found,
# such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
# Return -1 on failure.
a = myString.find("o")
print(a)

# S.rfind(sub[, start[, end]]) -> int
# Return the highest index in S where substring sub is found,
# such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
# Return -1 on failure.
r = myString.rfind("o")
print(r)

# Return a copy with all occurrences of substring old replaced by new.
b = myString.replace("world", "user")
print(b)

# Return a copy of the string converted to lowercase.
l = myString.lower()
print(l)

# Return a copy of the string converted to uppercase.
u = myString.upper()
print(u)

# Return a copy of the string with leading and trailing whitespace removed.
# If chars is given and not None, remove characters in chars instead.
s = myString.strip()
print(s)
Output
['Hello', 'world']
5
8
 Hello user 
 hello world 
 HELLO WORLD 
Hello world