🐍Python Master Class — Day 2 of ’n’ Days
Strings
Read
Python Master Class — Day 1 of ’n’ days
Strings
In Python, Strings are arrays of bytes representing Unicode characters. Python does not have a character data type.
A single character is simply a string with a length of 1.
Square brackets [ ] can be used to access elements of the string.
Python has built-in string class named “str”. String literals can be enclosed using either double or single quotes.
Python strings are immutable, which means they cannot be changed after they are created. Since strings can’t be changed, whenever we need to compute new values, new strings are created.
NOTE: immutable types cannot be changed once created. Whenever you do any operations on them, a new copy is returned back.
Internally Strings, for example, “PYTHON”, is represented as shown in the below figure.
Let’s work with some examples. Let’s put the below code in a file called
The First String Program
str-1.py
s = 'Hello Python'
print (s)
print (s[0]) # Get the first character
Output
Getting the length of String
To get the length of the string we can use the len() function.
s = 'Hello Python'
length = len (s)
print (length)
Output
12
Concatenating Strings
We can use the + operator to concatenate (or join) two strings.
# Concatenate stringfirst_name = "Nick"
last_name = "Fury"full_name = first_name + ' ' + last_nameprint (full_name)
Output
Nick Fury
Concatenating Number and String
Now to concatenate number and string together we first have to do the type conversion, i.e. the number needs to be converted to a string.
# Concatenate number and a stringage = 50# info = 'The age is ' + age (throws error)info = 'The age is ' + str(age)print (info)
In the above program we use the str() function to convert number to a string.
Multiline Strings
Let’s create some multiline strings
this_is_big = """I am gonna create a real big string.
Will this work. Ofcourse. I trust Python!"""print(this_is_big)
Output
I am gonna create a real big string.
Will this work. Ofcourse. I trust Python!
Unicode Strings
Unicode are character set beyond the standard ASCIIcharacter set. In short,in case you need to represent Mandarin, Hindi or any other language unicode comes into play.
READING: More about unicode http://xahlee.info/comp/unicode_intro.html
uni = u"i ♥ cats"
NOTE: Python 3 and above by default treats string as unicode. So the below declaration of the variable is same as above. The ‘u’ prefix is kept for backward compatibility.
uni = "i ♥ cats" # without 'u' prefix
Useful String Methods
Below is the commonly used or useful string methods. I have added comments to every method for quick usage reference.
SUCCESS TIP: I am using various variation of print function so that you can get more out of these examples. Read through comments and try the variations of the example.
The source code can be found in str-2.py under day-2 folder.
Snippet 1 — lower(), upper(), strip()
s = " Python is awesome! "# returns the lowercase version of the string
print (s.lower()) # returns uppercase version of the string
print (s.upper())# returns a string with whitespace removed from the start and end
print (s.strip())
Output
python is awesome!
PYTHON IS AWESOME
Python is awesome!
Snippet 2 — isalpha(), isdigit(), isspace()
# tests if the string chars are in the various character classess = "abc"
print (s + ' is alphabet => ' + str(s.isalpha()))s = "123"
print (s, " is a digit => ", s.isdigit())s = " " # note: there is an empty space between the double quotes
print (s, "is a space => ", s.isspace())
Output
abc is alphabet => True
123 is a digit => True
is a space => True
Snippet 3 — startswith(), endswith()
s = "/home/about"print (s, 'starts with /home => ', s.startswith('/home'))
print (s, 'ends with about => ',s.endswith('about'))
Output
/home/about starts with /home => True
/home/about ends with about => True
Snippet 4 — find()
# searches for the given other string (not a regular expression) within s,
# and returns the first index where it begins or -1 if not founds = 'Find the needle in the haystack'
print ('The word ""needle"" in the sentence', end='\n *')
print (s, end = '\n *')
print ("is found at position", s.find("needle"))
Output
The word ""needle"" in the sentence
*Find the needle in the haystack
*is found at position 9
Snippet 5 — replace()
# returns a string where all occurrences of 'old' have been replaced by 'new's = 'I am getting old again, but yet getting old is a better thing!'
print (s)
print (s.replace('old', 'new'))
Output
I am getting old again, but yet getting old is a better thing!
I am getting new again, but yet getting new is a better thing!
Snippet 6 — split()
# returns a list of substrings separated by the given delimiter.
# The delimiter is not a regular expression, it's just text.
# 'aaa,bbb,ccc'.split(',') -> ['aaa', 'bbb', 'ccc'].# As a convenient special case s.split() (with no arguments) splits # on all whitespace chars.s = "python,django,flask,numpy"
print("Splitting ", s, "by comma")
print(s.split(',') )
Output
Splitting python,django,flask,numpy by comma
['python', 'django', 'flask', 'numpy']
Snippet 7 — join()
# join() is opposite of split(), joins the elements in the given list
# together using the string as the delimiter.
# e.g. '---'.join(['aaa', 'bbb', 'ccc']) -> aaa---bbb---cccs = "****"
list = ["python","is","great"] #array
print ("Joining the list",list, 'with', s)
print (s.join(list))
Output
Joining the list ['python', 'is', 'great'] with ****
python****is****great
NOTE: Arrays will be covered in subsequent articles
Source Code: https://github.com/rajeshpillai/python-tutorials
ATTENTION: This is a first draft. Watch out for more detailed updates.
History
- 16-Nov-2019 — First Version