Python – Strings

Python Strings

Python – Strings: Strings are one of Python’s most popular data types. It’s a text storage device. It is made by enclosing characters in single or double quote marks. The = symbol can be used to assign it to a variable.

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

Python Multi-line Strings

Enclosing the block in three single quotation marks or three double quotation marks creates a multi-line string.

MyString = """Python 
programming"""

MyString = '''Python 
programming'''

Access character of a String

The index number of a character (also known as an element) in a string can be used to access it. The index number in Python begins with 0 in the forward direction and -1 in the reverse direction. The indexing idea of a string is depicted in the diagram below.

String Indexing:

Python String Indexing

The following example shows how to retrieve a character in a string by its index number.

MyString = 'Python'

#forward indexing
print(MyString[0]) 

#backward indexing 
print(MyString[-1])

The output of the above code will be:

P 
n

Access the range of characters of a String

A statement like [startIndex: endIndex] can be used to select a range of characters in a string, with the end index being omitted. If the start index and end index aren’t specified, the string’s first and last index numbers are used instead.

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

print(MyString[6:])
print(MyString[:-7],"\n")

print(MyString[:])

The output of the above code will be:

Learn
Learn

Python
Learn

Learn Python

String Length

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

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

The output of the above code will be:

12

Check a character(s) in the String

The if control statement is used to determine if or not the string includes the supplied character(s).

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.')

The above code will give the following output:

Yes, It is present in the string.

String Concatenation

The + operator can be used to combine two strings together.

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

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

The above code will give the following output:

LearnPython
Learn Python

String format() Method

The + operator cannot be used to combine strings and integers. The format method is used to combine a string with a number. The user can supply parameter(s) to the format() function, which are then inserted in the appropriate placeholder. There is no limit to the number of arguments that may be sent to this method. Along with placeholders, an index number (beginning with 0) can be utilised. Please see the following 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))

The above code will give the following 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

There are a lot of string methods in Python. A few popular string functions are explained in this section.

  • lower(): Returns string in lowercase
  • upper(): Returns string in uppercase
  • strip(): Removes whitespaces from the 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 the number of occurrences of a specified character(s) in the string

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

In Python, the lower(), upper(), and strip() functions are demonstrated in the sample below.

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

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

The above code will give the following output:

learn python
LEARN PYTHON
Learn Python

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

When working with a string, the replace(), split(), and count() methods are used in the example below.

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'))

The above code will give the following output:

Learn C++
['Learning', 'Python', 'is', 'fun']
2

Also Read: Java – Strings

Leave a Reply

Your email address will not be published. Required fields are marked *