You have already been introduced with strings.
a = "Hey there"
Like list, string is also a collection. They are collection of characters.
a = "Hey there" print a
Like list, we can also use 'len' and 'slice' for string.
a = "Hello World" print len(a) print a[1:4]
But strings are immutable. This means that we that we can't change any element of a string. So, we can't do a='b' as we did with lists. Let's see what happens when we try to write this.
a = "Hello World!" a = 'b'
TypeError: 'str' object does not support item assignment
You got this error because you can't change any element of a string.
Let's play with string
import string a = "Hey there world" print a.split()
import string - We are making use of Python's string directory. It contains many useful functions. See more at Python's official documentation.
split function splits a string when it encounters a space(" ") and put them into a list.
To split at a particular place.
We can also use the split function to split the string with something other than a 'space'. Let's see how:
import string a = "Buggy bug buggy bug, where are you my buggy bug!" print a.split('b')
Here we wanted our string to split at 'b'. So, we passed 'b' to the 'split()' function and it's done.
Comparison of strings in Python is very simple. We just use '==', '<,' ,'>' ,'>=' , '<=' operators. Let's see an example:
a = raw_input() if a>"abc": print 'your word comes after abc' elif a<"abc": print 'your word comes before abc' else: print 'your word is abc'
your word comes after abc
See this example of taking a string input of numbers which are separated by a space and storing them in a list as ints.
a = raw_input() b = a.split() print b c = map(int,b) print c
['1', '2', '3', '4', '5', '6', '7', '8', '9']
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Here, the 'split' split the string and stored them into a list with every space. And the'map' function changed all the strings of the list to ints.
Some more useful functions
Capitalizes the first character of a string
import string a = "hey there world!" print string.capitalize(a)
Turns every character of the string into lower case.
import string a = "hEy tHEre WOrld!" print string.lower(a)
Turns every character of the string into upper case.
import string a = "hEy tHEre WOrld!" print string.upper(a)
Joins the element of a list to a string. It will be clear by the example given below.
import string a = ["hEy", "tHEre", "WOrld!"] print string.join(a) print string.join(a,";")
Inverts the case of a string
import string a = "hEy tHEre WOrld!" print string.swapcase(a)
I have shown you many useful things to do with string. But there are a lot more functions to explore. You can use them whenever you need them from official documentation.
If you don't practice, you don't deserve to win.