Introduction to strings in python


In Python, the strings should be created by simply enclosing the characters in quotes. Python does not support the character types. These are treated as length-one strings, and are also considered as substrings. Substrings are immutable and can’t be changed once created.

Strings are the ordered blocks of text that are enclosed in single or double quotations. Thus, whatever is written in quotes, is considered as string. Though it can be written in single or double quotations, double quotation marks allow the user to extend strings over multiple lines without backslashes, which is usually the signal of continuation of an expression, e.g., ‘abc’, “ABC”.

Concatenation and Repetition

  • Strings are concatenated with the +sign:

>>> ‘abc’+‘def’


  • Strings are repeated with the *sign:

>>> ‘abc’*3


Indexing and Slicing Operation

  • Python starts the indexing at ‘0’
  • A string s will have indexes running from 0 to len(s)-1 (where len(s) is the length of s) in integer quantities.
  • S[i] fetches the ‘i’th element in the s.

Built-in String Methods

Following are the built-in String Methods that can be used in Python:

  • capitalize() – This method is used to capitalize the first letter of string.
  • count(str, beg= 0, end=len(string)) – Used to count how many times  the str occurs in string or in a substring of string, if beginning index ‘beg’ and ending index ‘end’ are given.
  • encode(encoding=‘UTF-8’,errors=‘strict’) – This method is used to return the encoded string version of string; on error, default raises a ValueError, unless the error is given with ‘ignore’ or ‘replace’.
  • decode (encoding=‘UTF-8’, errors=‘strict’) – This method is used to decode the string using the codec registered for Encoding. Encoding defaults to the default string function.
  • index(str, beg=0, end=len(string))- Same as find(), but it raises an exception if str is not found.
  • max(str)- Used to return the max alphabetical character from the string str.
  • min(str)- This is used to return the min alphabetical character from the string str.
  • replace(old, new [, max])- This method is used replace all the occurrences of ‘old’ in string with ‘new’ or maximum occurrences if max is given.
  • upper()- This method is used to convert the lowercase letters in a string to uppercase.

If you have any queries? Mention them in the comments section and we will clarify you.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s