Foundations of Python

You are currently auditing this course.
100 / 134

Lists and Strings

A list is a sequence of values while a string is a sequence of characters.But, a list of characters is not a string.

We can convert a string to a list of characters using list function,

s = "CloudxLab"
l = list(s)
print (l)

It prints the list as ['C', 'l', 'o', 'u', 'd', 'x', 'L', 'a', 'b']

The list function splits a string into individual letters. Suppose, if we want to break a long string into words we can use split function to create a list of words,

s = "I am learning Python at CloudxLab"
sp = s.split()
print (sp)

It prints the list of words in s as ['I', 'am', 'learning', 'Python', 'at', 'CloudxLab']

We can also split the string on the basis of a certain character or a substring called as a delimiter. It is an optional argument for the split function.

s = "I am learning Python at CloudxLab"
sp = s.split("am")
print(sp)

It splits the string considering "am" as a pivot and prints a list of remaining substrings as
['I ', ' learning Python at CloudxLab']

What if there are more than one "am" in the original string? Try that in the notebook.

We can join the split strings using join function,

delimiter = "am"    
print(delimiter.join(sp))

It adds the pivot between the words in the list and prints the original string I am learning Python at CloudxLab

INSTRUCTIONS
  • Define a function with the name str_list_func that takes a string argument
  • Interchanges the 1st and last letter of each word in that argument and then return the resulting string. i.e. l and g in leaning should be interchanged with each other and rest of the letters in that word should remain at their position only (learning will become gearninl)

Sample Input: 'I am learning Python at CloudxLab'

Sample Output: 'I ma gearninl nythoP ta bloudxLaC'


Loading comments...