Working with strings in Python


Working with strings in Python

String is a most used data type in python programming. A string is simply a series of characters. Anything inside quotes is considered as a string in Python, we can use either single or double quote. As python is a case sensitive language so string 'an' is considered different from string 'An'. In python string represented by data type "str".

Note: String is an immutable object in python. So, it cannot be modified.

Representation of "string" datatype

"This is a string."
'This is also a string.'
'string with single quote(')'
# SyntaxError: invalid syntax
'string with single quote(\')'
"string with double quote(\")"
"single quote inside a double quoted string(') "
'double quote inside a single quoted string(")'
# storing string in a variable/name
full_name = 'Anjaneyulu Batta'
print(full_name)
# Anjaneyulu Batta

To represent the string we place the data inside a single quote(') or a doouble quote("). But, sometimes it may be required to use a single quote inside a single quoted string and double quote inside a double quoted string. In such cases we can simply place a backslash(\) character just before the single quote or a double quote.

Basic operations of strings in python

String is a collection of charactors. we can access these charactors with indexes. Index starts from zero(0). Negative index is also supported.

Python Strings

Let's cosider the below code

my_str = 'Hello'
# Get first charactor
first_char = my_str[0]
sec_char = my_str[1]
# Get substring from 1 to 3
sub_string = my_str[1:4]

We have used slicing operation on strings to get a substring. Slicing Method Signature is "S[start:end]".

Note: End index is not included in the resulted string.

 

Working with string methods in python

  • working with "capitalize" string method in python
    # method signature:  S.capitalize()  --> str
    s = "hello WorlD"
    out = s.capitalize()
    print(out)
    # Output: Hello world
    
    "capitalize" means making the first character of the string to upercase and remaining characters to lower case.
  • working with "title" string method in python
    # method signature: S.title()  --> str
    s = 'heLLo worLd'
    out = s.title()
    print(out)
    # Output: Hello World
    
    "title" case means words start with title case characters or upper case characters and all remaining cased characters have lower case.
  • working with "lower" string method in python
    # method signature: S.lower() --> str
    s = 'heLLo worLd'
    out = s.lower()
    print(out)
    # Output: hello world
    
    "lower" method converts all the charactors in the given string in lower case letters and returns it.
  • working with "upper" string method in python
    # method signature: S.upper()  --> str
    s = 'heLLo worLd'
    out = s.title()
    print(out)
    # Output: HELLO WORLD
    
    "upper" method converts all the charactors in the given string in upper case letters and returns it.
  • working with "count" string method in python
    # method signature: S.count(sub_string, start=0, end=len(S)) -> int
    s = 'This is my world'
    count = s.count("is")
    print(count)
    # Output: 2
    
  • working with "find" string method in python
    # method signature: S.count(sub_string, start=0, end=len(S)) -> int
    s = 'heLLo worLd'
    out = s.find('Lo')
    print(out)
    # Output: 3
    
    Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
  • working with "index" string method in python
    # method signature: S.index(sub_string, start=0, end=len(S)) -> int
    s = 'heLLo worLd'
    out = s.index('w')
    print(out)
    # Output: 6
    
    It returns the index of first occurence of the substring in a given string. It raises valueError exception when  the substring is not found.
  • working with "split" string method in python
    # method signature: S.split(sep=None, maxsplit=-1) -> list of strings
    s = 'I am learning python'
    out = s.split(sep=' ', maxsplit=2)
    print(out)
    # Output: ['I', 'am', 'learning python']
    out = s.split()
    print(out)
    # Output: ['I', 'am', 'learning', 'python']
    Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.
  • working with "replace" string method in python
    # method signature: S.replace(old, new, count) -> str
    s = 'I am learning python. I am searhing in google.'
    out = s.replace('am', 'AM', 1)
    print(out)
    # Output: I AM learning python. I am searhing in google.
    out = s.replace('am', 'AM')
    print(out)
    # Output: I AM learning python. I AM searhing in google.
    Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
  • working with "strip" string method in python
    # method signature: S.strip([chars]) -> str
    s = '    Search for python in Google    '
    out = s.strip()
    print(out)
    # Output: Search for python in Google
    s = 'eeepy(e)thoneee'
    out = s.strip('e')
    print(out)
    # Output: py(e)thon
    
    Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead.
  • working with "lstrip" string method in python
    # method signature: S.lstrip([chars]) -> str
    s = '   python   '
    out = s.lstrip()
    print(out)
    # Output: 'python   '
    s = 'eeepy(e)thoneee'
    out = s.lstrip('e')
    print(out)
    # Output: py(e)thoneee
    Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead.
  • working with "rstrip" string method in python
    # method signature: S.rstrip([chars]) -> str
    s = '   python   '
    out = s.rstrip()
    print(out)
    # Output: '   python'
    s = 'eeepy(e)thoneee'
    out = s.rstrip('e')
    print(out)
    # Output: eeepy(e)thon
    It returns a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead.
  • working with "join" string method in python
    # method signature: S.join([iterables]) -> str
    out = ','.join(['Ravi', 'Ram', 'Diana', 'Raheem'])
    print(out)
    # Output: Ravi,Ram,Diana,Raheem
    
    It returns a string which is the concatenation of the strings in the iterable.  The separator between elements is S.
  • working with "swapcase" string method in python
    # method signature: S.swapcase() -> str
    s = 'hello WOrLD'
    out = s.swapcase()
    print(out)
    # Output: HELLO woRld
    
    It returns a copy of S with uppercase characters converted to lowercase and vice versa.
  • working with "format" string method in python
    # method signature: S.format(*args, **kwargs) -> str
    out = 'My name is {0} {1}'.format("Anjaneyulu", "Batta")
    print(out)
    # Output: My name is Anjaneyulu Batta
    out = 'My name is {first_name} {last_name}'.format(
         first_name="Anjaneyulu", last_name="Batta"
    )
    print(out)
    # Output: My name is Anjaneyulu Batta
    
    Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}').
  • working with "partition" string method in python
    # method signature: S.partition(sep) -> (head, sep, tail)
    s = 'searching for python'
    out = s.partition('for')
    print(out)
    # Output: ('searching ', 'for', ' python')
    Search for the separator sep in S, and return the part before it, the separator itself, and the part after it.  If the separator is not found, return S and two empty strings.

Working with boolean string methods in python

  • working with "startswith" string method in python
    # method signature: S.startswith(prefix, start=0, end=len(S)) -> bool
    s = 'heLLo worLd'
    out = s.startswith('he')
    print(out)
    # Output: True
    out = s.startswith('Good')
    print(out)
    # Output: False
    
    Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
  • working with "endswith" string method in python
    # method signature: S.endswith(prefix, start=0, end=len(S)) -> bool
    s = 'heLLo worLd'
    out = s.endswith('rLd')
    print(out)
    # Output: True
    out = s.endswith('Good')
    print(out) # Output: False
    
    Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
  • working with "isalnum" string method in python
    # method signature: S.isalnum() -> bool
    s = '1234abcd'
    out = s.isalnum()
    print(out)
    # Output: True
    s = 'This is # letter 1234'
    out = s.isalnum()
    print(out)
    # Output: False
    Return True if all characters in S are alphanumeric, False otherwise.
  • working with "isalpha" string method in python
    # method signature: S.isalpha() -> bool
    s = '1234abcd'
    out = s.isalpha()
    print(out)
    # Output: False
    s = 'alphabetsonly'
    out = s.isalpha()
    print(out)
    # Output: True
    Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise.
  • working with "isdecimal" string method in python
    # method signature: S.isdecimal() -> bool
    s = '1234abcd'
    out = s.isdecimal()
    print(out)
    # Output: False
    s = '12345'
    out = s.isalpha()
    print(out)
    # Output: True
    
    It return True if there are only decimal characters in S, False otherwise.
  • working with "isdigit" string method in python
    # method signature: S.isdigit() -> bool
    s = '1234abcd'
    out = s.isdigit()
    print(out)
    # Output: False
    s = '1234'
    out = s.isdigit()
    print(out)
    # Output: True
    Return True if all characters in S are digits and there is at least one character in S, False otherwise.
  • working with "islower" string method in python
    # method signature: S.islower() -> bool
    s = 'Hello world'
    out = s.islower()
    print(out)
    # Output: False
    s = 'hello world'
    out = s.islower()
    print(out)
    # Output: True
    Return True if all cased characters in S are lowercase and there is at least one cased character in S, False otherwise.
  • working with "isupper" string method in python
    # method signature: S.isupper() -> bool
    s = 'Hello world'
    out = s.isupper()
    print(out)
    # Output: False
    s = 'HELLO'
    out = s.isupper()
    print(out)
    # Output: True
    Return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise.
  • working with "isnumeric" string method in python
    # method signature: S.isnumeric() -> bool
    s = '1234.234g'
    out = s.isnumeric()
    print(out)
    # Output: False
    s = '12355600'
    out = s.isnumeric()
    print(out)
    # Output: True
    Return True if there are only numeric characters in S, False otherwise.
  • working with "isspace" string method in python
    # method signature: S.isspace() -> bool
    s = 'Hello world'
    out = s.isspace()
    print(out)
    # Output: False
    s = '\n  \t'
    out = s.isspace()
    print(out)
    # Output: True
    Return True if all characters in S are whitespace and there is at least one character in S, False otherwise.
  • working with "istitle" string method in python
    # method signature: S.istite() -> bool
    s = 'hello world'
    out = s.istite()
    print(out)
    # Output: False
    s = 'Hello World'
    out = s.istite()
    print(out)
    # Output: True
    Return True if S is a titlecased string and there is at least one character in S, i.e. upper- and titlecase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise.

Reference: 
https://docs.python.org/2/library/string.html