Python : Strings
During this post we will talk about Python data type Strings and its some basic operations that could perform in some simple examples to explain its functions through some modules and their methods.
In Python string has simple alphanumeric characters enclosed single or double quotes to assign variables. Let’s take some examples of strings.
>>> a="string1" >>> type(a)
We can access string slice or sub-strings along indexes like below.
>>> a="string1" >>> a 's' >>> a[0:4] 'stri'
Let’s do some other stuff, how can we simply ask user to enter some string value through keyboard.
string = raw_input("please write down one string : ") print "Your string was : ", string print "Type was : ", type(string)
Output for same
please write down one string : python Your string was : python Type was :
We can notice in above output that we ask user to put some string that we can work with or Just print in simple way as we did above.
With strings we could do many operations like some example mentioned below …
string = raw_input("please write down one string : ") print string.capitalize() print len(string) print string.split() print string.upper() print string.lower() print string.isspace() print string.count("a") print string.replace("Python","Bash") print string.swapcase()
please write down one string : Python is Scripting Language Python is scripting language 28 ['Python', 'is', 'Scripting', 'Language'] PYTHON IS SCRIPTING LANGUAGE python is scripting language False 2 Bash is Scripting Language pYTHON IS sCRIPTING lANGUAGE
Although i should explain every options show above in details to you in same post, but i like to search a bit yourself or read through python help like below
>>> help(a.capitalize) Help on built-in function capitalize: capitalize(...) S.capitalize() -> string Return a copy of the string S with only its first character capitalized.
So i suggest its always good to find out ways to search some help while reading or learning, this will help you to understand many more concepts that you looking for.In python string, we have so many operations and its only possible to discuss very few of them.
some special operator to work on Strings.
>>> a*2 'stringstring' >>> a + " " + a 'string string' >>> a[0:2] 'st' >>> a[-6:-4] 'st' >>> a[-1:] 'g' >>> a[:-6] '' >>> a[:-5] 's' >>> "s" in a True
So as we saw above in many ways we can work on String in python, that help to work in any python program. These methods and functions used just a very basic one, we have various which could only be practice only when we get deeper knowledge of python during further proceeding of this course.