Python - Strings

Python - Strings


Previous Page

Python Strings

Strings are one of the most common data types in Python. It is used for storing text. It can be created by enclosing characters either in single quotation marks or double quotation marks. It can be assigned to a variable using = sign.

MyString = "Hello World!"
MyString = 'Hello World!'

Python Multi-line Strings

Multi-line string can be created by enclosing the block either in three single quotation marks or three double quotation marks.

MyString = """Python 
programming"""

MyString = '''Python 
programming'''

Access character of a String

A character (also called element) of a string can be accessed with it's index number. In Python, index number starts with 0 in forward direction and -1 in backward direction. The below figure and example describe the indexing concept of a string.

String Indexing:

Python String Indexing

MyString = 'Python'

#forward indexing
print(MyString[0]) 

#backward indexing 
print(MyString[-1])  

Output

P 
 
n   

Access range of characters of a String

Range of characters of a string can be selected using statement like [start_index : end_index] where end_index is excluded. If start_index and end_index are not mentioned then it takes first and last index numbers of the string respectively.

MyString = 'Learn Python'
print(MyString[0:5])
print(MyString[-12:-7])

print(MyString[6:])
print(MyString[:-7])

print(MyString[:])

Output

Learn
Learn

Python
Learn

Learn Python   

String Length

The len() function can be used to find out total number of characters in the string.

MyString = 'Learn Python'
print(len(MyString))

Output

12

Check a character(s) in the String

If control statement is used to check whether the string contains specified character(s) or not.

MyString = 'I am learning Python programming.'
if 'programming' in MyString:
  print('Yes, It is present in the string.')
else:
  print('No, It is not present in the string.')

Output

Yes, It is present in the string.

String Concatenation

Two strings can be joined using + operator.

text_1 = 'Learn'
text_2 = 'Python'
MyString = text_1 + text_2
print(MyString)

MyString = text_1 + " " + text_2
print(MyString)

Output

LearnPython

Learn Python

String format() Method

Strings can not be added with numbers by using + operator. For combining string with a number, format method is used. A user can pass parameter(s) in format() method, which is further placed into its respective placeholder {}. This method can take unlimited number of parameters. Along with this, an index number (starts with 0) can also be used with placeholders. Please see example below:

Example:


in_time = 9
out_time = 18
MyString = "I will reach office at {} hrs and leave office at {} hrs."
print(MyString.format(in_time, out_time))

in_time = 9
out_time = 18
MyString = "I will reach office at {1} hrs and leave office at {0} hrs."
print(MyString.format(out_time, in_time))

Output

I will reach office at 9 hrs and leave office at 18 hrs.

I will reach office at 9 hrs and leave office at 18 hrs.

String Methods

Python has number of . Here, few very common string functions are discussed.

  • lower(): Returns string in lowercase
  • upper(): Returns string in uppercase
  • strip(): Removes whitespaces from start and end of the string
  • replace(): replace specified character(s) with another specified character(s)
  • split(): Split the string by specified separator and returns substrings in a list.
  • count(): Returns number of occurrence of specified character(s) in the string

Example: lower(), upper() and strip() String Methods


MyString = "Learn Python"
print(MyString.lower())
print(MyString.upper())

MyString = "  Learn Python  "
print(MyString.strip())

Output

learn python

LEARN PYTHON

Learn Python

Example: replace(), split() and count() String Methods


MyString = "Learn Python"
print(MyString.replace("Python", "C++"))

MyString = "Learning Python is fun"
print(MyString.split(" "))

MyString = "This is Python programming."
print(MyString.count('is'))

Output

Learn C++

['Learning', 'Python', 'is', 'fun']

2




Recommended Pages

  • Next Page

  • String Methods & Functions
    MethodsDescription
    Converts first character of first world into uppercase and rest into lowercase
    Converts string into lower case
    Python Strings Returns a centered string
    Returns the number of times a specified value occurs in a string
    Strings are one of the most common data types in Python. It is used for storing text. It can be created by enclosing characters either in single quotation marks or double quotation marks. It can be assigned to a variable using Returns an encoded version of the string
    = Returns true if the string ends with the specified value
    sign. Sets the tab size of the string
    Searches the string for a specified value and returns the position of where it was found
    Formats specified values in a string
    Formats specified values in a string
    MyString = "Hello World!" MyString = 'Hello World!' Returns the index number for first occurrence of specified character sequence in the string
    Returns true when all characters of the string are alphanumeric, else returns false
    Returns true when all characters of the string are alphabet, else returns false
    Python Multi-line Strings Returns true when all characters of the string are decimals, else returns false
    Returns true when all characters of the string are digits, else returns false
    Multi-line string can be created by enclosing the block either in three single quotation marks or three double quotation marks. Returns true when the string is an identifier, else returns false
    Returns true when all characters of the string are in lowercase, else returns false
    Returns true when all characters of the string are numeric, else returns false
    Returns true when all characters of the string are printable, else returns false
    MyString = """Python programming""" MyString = '''Python programming''' Returns true when all characters of the string are whitespaces, else returns false
    Returns true when the characters of the string is in title format, else returns false
    Returns true when all characters of the string are in uppercase, else returns false
    Access character of a String Joins the elements of an iterable to the end of the string
    Returns a left justified version of the string
    A character (also called element) of a string can be accessed with it's index number. In Python, index number starts with 0 in forward direction and -1 in backward direction. The below figure and example describe the indexing concept of a string. Converts all characters of the string into lowercase
    Returns a left trim version of the string
    String Indexing: Returns a translation table to be used in translations
    Returns a tuple where the string is parted into three parts
    Returns a string where a specified value is replaced with a specified value
    Searches the string for a specified value and returns the last position of where it was found
    Searches the string for a specified value and returns the last position of where it was found
    Example Returns a right justified version of the string
    Returns a tuple where the string is parted into three parts
    MyString = 'Python' #forward indexing print(MyString[0]) #backward indexing print(MyString[-1]) Splits the string at the specified separator, and returns a list
    Returns a right trim version of the string
    Splits the string at the specified separator, and returns a list
    Splits the string at line breaks and returns a list
    Returns true if the string starts with the specified value
    Output Returns a trimmed version of the string
    convert all lowercase characters into uppercase and uppercase characters into lowecase
    P n Converts all characters of the string in title format.
    Returns a translated string
    Converts all characters of the string into uppercase
    Access range of characters of a String Fills the string with a specified number of 0 values at the beginning
    FunctionsDescription
    Returns total number of characters in the string.

    Previous Page