Learn Python Fundamental in 30 Days — Day 3(Strings)

devops everyday challenge
devops-challenge
Published in
4 min readMay 3, 2017

--

Strings is just a sequence of characters letters,special characters,space,digits

We can use single/double quote to represent a string

>>> x = “hello”>>> x
‘hello’
>>> x = ‘hello’>>> x
‘hello’

Reason for using single vs double quote in a string

>>> ‘I don’t know you’
File “<stdin>”, line 1
‘I don’t know you’
^
SyntaxError: invalid syntax
>>> “I don’t know you”
“I don’t know you”

Operations on Strings

To determine the length of string

>>> len(“hello”)
5

# Concatenation is done using + operator(or in other words we can say, we have overloaded it)

>>> "hello " + "world"
'hello world'

# Successive Concatenation on string

>>> x = "hello "
>>> x * 3
'hello hello hello '

# Indexing on string(Indexing start with zero not one)

>>> x[0]
‘h’

# To get the last element

>>> x[-1]'o'

# Try to get something out of range

>>> x[5]
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
IndexError: string index out of range

# We can slice the string

>>> x[0:3]'hel'# OR>>> x[:3]
'hel'
# To grab everything>>> x[:]
'hello'

# We can also use join() to join string

>>> “-”.join([“hello”,”how”,”are”,”you”])
‘hello-how-are-you’

# Then we can call split() to divide a string into a list(Without an argument split() divides on whitespace)

>>> y
‘hello-how-are-you’
>>> y.split(“-”)
[‘hello’, ‘how’, ‘are’, ‘you’]
# Split by specific element>>> x = "hello world"
>>> x.split('w')
['hello ', 'orld']

#Partition() method divides a string into three, around a separator(prefix,separator,suffix)

>>> "hastalevista".partition("le")('hasta', 'le', 'vista')

# As it return a tuple it’s useful to destructure the result

>>> x,y,z = “hastalevista”.partition(“le”)
>>> x
‘hasta’
>>> y
‘le’
>>> z
‘vista’

# We can _ as a dummy name for the separator

>>> a,_,b = "hello-world".partition("-")>>> a'hello'>>> b'world'>>> _'-'

NOTE the major difference between split and partition

# Partition based on first occurrence and return a seperator
>>> x.partition(‘l’)
(‘he’, ‘l’, ‘lo’)
# It split the string on every occurrence of 'l'
>>> x.split(‘l’)
[‘he’, ‘’, ‘o’]

# Format() is used to insert values into strings,replacement fields delimited by { and }

>>> "My name is {0} and my age is {1}".format("Prashant",33)'My name is Prashant and my age is 33'

String Methods

Objects in Python usually have built-in methods. These methods are functions inside the object that can perform actions or command on the object itself

  • Upper case a string
>>> x
‘hello’
>>> x.upper()
‘HELLO’
  • Lower case a string
>>> x.lower()
‘hello’
  • Capitalize first word in string
>>> x.capitalize()
‘Hello world’
  • Count how many o in string
>>> x.count(“o”)
2
  • Location of first occurrence of o
>>> x.find(“o”)
4
  • isalnum() will return True if all characters in x are alphanumeric
>>> x.isalnum()
True
  • isalpha() wil return True if all characters in x are alphabetic
>>> x.isalpha()
True
  • islower() will return True if all cased characters in x are lowercase and there is at least one cased character in x, False otherwise.
>>> x.islower()
True
  • To check if strings ends with particular character
>>> x.endswith(‘o’)
True

NOTE:

Please be careful with these type of operations

  • Strings are immutable: Once it’s created we can’t change it
>>> x
‘hello’
>>> x[0] = ‘y’
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
TypeError: ‘str’ object does not support item assignment

However you can do it like this

>>> x = “y” + x[1:]
>>> x
‘yello’
  • Multiply string with string with lead to an error
>>> “1” * “ab”Traceback (most recent call last):File “<stdin>”, line 1, in <module>TypeError: can’t multiply sequence by non-int of type ‘str’
  • Out of range error as len starts with zero
>>> x = "hello">>> len(x)5>>> x[len(x)]Traceback (most recent call last):File "<stdin>", line 1, in <module>IndexError: string index out of range
  • Case matter in Python(hello and HELLO are not equal)
>>> x'hello'>>> x == "HELLO"False
  • Some tricky stuff ,print everything except last character
>>> x[:-1]'hell'
  • Use of step(print with an increment of 2)
>>> x[0:4:2]'hl'
  • Famous interview question(Reverse a string ;-))
>>> x[::-1]'olleh'

Exercise

What is the output of:

  1. “a” + “bc”
  2. What is the difference in output of “ab” * 2 vs “ab” * “2”
  3. What is the difference in output of “abcde”[3] vs “abcde”[5]
  4. What is the difference in output of “abcde”[0:2] vs “abcde”[:2] vs “abcde”[2:]
  5. If x = “hello” ,what is len(x) and x(len(x))

So this end of Day3, In case if you are facing any issue, this is the link to Python Slack channel https://devops-myworld.slack.com

Please send me your details

  • First name
  • Last name
  • Email address

to devops.everyday.challenge@gmail.com, so that I will add you to this slack channel

HAPPY CODING!!

--

--