String manipulation in Python is very different from the ones that we have in other programming languages.
Here are few examples of string manipulation in Python:
Strings start from 0 in Python.
Will give you an output of 'T'
The fun starts with ':' symbol
This tells Python to display string from 0 to end of string.
The output for this will be:
Few important slicing and dicing options are given below. Please try it out by yourself all these things and more:
List also has similar slicing and dicing options. However, few key differences between strings and lists are that:
As an additional activity, explore the different methods that are available in the Python String object and compare them with that of the list object.
Here are few examples of string manipulation in Python:
Assignment operation
As we saw in earlier posts, there is no type and length declaration for string. It is a straight-forward assignment operation.
pyStr = 'This is a Python test string'
Strings start from 0 in Python.
pyStr[0]
Will give you an output of 'T'
The ':' symbol
pyStr[0:]
This tells Python to display string from 0 to end of string.
pyStr[0:6]
The output for this will be:
'This i'
Few important slicing and dicing options are given below. Please try it out by yourself all these things and more:
pyStr[::2] #Prints every second letter of the string starting from 0 #'Ti saPto etsrn d' is the output pyStr[::-1] #reverses the string pyStr[1::3] #Starts from 1, prints every 3rd character pyStr[::-2] #reverses string but only every alternate character is considered #'te aotdagit stnhy ish' pyStr = pyStr + ' additional text' #adds more text pyStr[20] = 'V' #does not work. String is not mutable like this. pyStr = pyStr - 'additional text' #Doesn't work either.
List
List also has similar slicing and dicing options. However, few key differences between strings and lists are that:
- Items in the list can be modified by simple assignment operator.
- '.append(obj)' method should be used to add elements to the list.
- List object has methods like 'pop', 'clear', 'index', 'sort', etc. whereas string object has its own set of methods.
list_a = ['apple','banana','mango','jack fruit'] #List assignment. list_a[::1] #Same as string. list_a[::-1] #Reverses and prints a list but does not alter the list. list_a[1] = 'pear' #Works in the list. Replaces 'banana' with 'pear'. list_a.append('fig') #Appends 'fig' to the end of the list. list_a[4] = 'fig' #Does not work. Index out of range.
As an additional activity, explore the different methods that are available in the Python String object and compare them with that of the list object.
No comments:
Post a Comment