Strings in Python

Strings in Python with Examples

In this article, I will discuss Strings in Python with Examples. Please read our previous article discussing Looping Statements in Python with examples. You will understand the following pointers in detail at the end of this article.

  1. What is a string in Python?
  2. What is Slicing in Python?
  3. What is Immutable in Python?
  4. Strings are immutable in Python
  5. Mathematical operators on string objects in Python
  6. How do you find the length of a string in Python?
  7. How to remove spaces from a string in Python?
  8. How do you Find substrings in a string in Python?
  9. How do you Count substrings in a given String in Python?
  10. How to replace a string with another string in Python?
  11. Does the replace() method modify the string objects in Python?
  12. How to Split a string in Python?
  13. How to Join strings in Python?
  14. How do you change cases of string in Python?
  15. How to Formatting the Strings in Python?
Reminder

We have already learned the first Hello World program in Python. In that program, we print a group of characters by using the print() function. Those groups of characters are called a string.

Program to print string (Demo1.py)
print(“Welcome to Python programming”)
Output: Welcome to Python programming

What is a string in Python?

A string is a group of characters enclosed within single, double, or triple quotes. We can say the string is a sequential collection of characters.

What is a string in Python?

Program to print employee information (Demo2.py)
name = "Balayya"
emp_id = 20
print("Name of the employee: ", name)
print("employee id is :", emp_id)
Output:

Strings in Python with Examples

Note: Generally, to create a string, the most used syntax is double quotes syntax.

When are single and triple-double quotes are used?

If you want to create multiple lines of string, then triple-single or triple-double quotes are the best to use.

Program to print multi-line employee information (Demo3.py)
loc1 = """XYZ company
While Field
Bangalore"""
loc2 = """XYZ company
Banglore
Human tech park"""
print(loc1)
print(loc2)
Output:

Strings in Python with Examples

Note: Inside string, we can use single and double quotes

Program to use single and double quotes inside a string (Demo4.py)
s1 = "Welcome to 'python' learning"
s2 = 'Welcome to "python" learning'
s3 = """Welcome to 'python' learning"""
print(s1)
print(s2)
print(s3)
Output:

Strings in Python with Examples

The Empty string in Python:

If a string has no characters, it is called an empty string.

Program to print an empty string (Demo5.py)
s1 = ""
print(s1)

Output:

Accessing string characters in Python:

We can access string characters in Python by using,

  1. Indexing
  2. Slicing
Indexing:

Indexing means the position of the string’s characters where it is stored. We need to use square brackets [] to access the string index. The string indexing result is string type. String indices should be integers; otherwise, we will get an error. We can access the index within the index range; otherwise, we will get an error.

Python supports two types of indexing.
  1. Positive indexing: The position of string characters can be a positive index from left to right direction (we can say forward direction). In this way, the starting position is 0 (zero).
  2. Negative indexing: The position of string characters can be negative indexes from right to left direction (we can say backward direction). In this way, the starting position is -1 (minus one).
Diagram representation

Accessing string characters in python using indexes

Note: If we try to access characters of a string without a range index, we will get an error as IndexError.

Example: Accessing a string with an index in Python (Demo6.py)
wish = "Hello World"
print(wish[0])
print(wish[1])

Output:

Python Strings with Examples

Example: Accessing a string with float index in Python (Demo7.py)
wish = "Hello World"
print(wish[1.3])
Output:

Accessing a string with float index in Python

Example: Accessing a string without a bound index (Demo8.py)
wish = "Hello World"
print(wish[100])
Output:

Accessing a string without of bound index

Example: Accessing a string with a negative index (Demo9.py)
wish = "Hello World"
print(wish[-1])
print(wish[-2])
Output:

Accessing a string with a negative index

Example: Printing character by character using for loop (Demo10.py)
name ="Python"
for a in name:
   print(a)
Output:

Printing character by character using for loop in Python

What is Slicing in Python?

A substring of a string is called a slice. A slice can represent a part of a string from a string or a piece of string. The string slicing result is string type. We need to use square brackets [] in slicing. In slicing, we will not get any index out-of-range exceptions. In slicing, indices should be integer or None or __index__ method otherwise, we will get errors.

Syntax:

What is Slicing in Python?

Example:

What is Slicing in Python?

Different Cases:

wish = “Hello World”

  1. wish [::] => accessing from 0th to last
  2. wish [:] => accessing from 0th to last
  3. wish [0:9:1] => accessing string from 0th to 8th means (9-1) element.
  4. wish [0:9:2] => accessing string from 0th to 8th means (9-1) element.
  5. wish [2:4:1] => accessing from 2nd to 3rd characters.
  6. wish [:: 2] => accessing entire in steps of 2
  7. wish [2 ::] => accessing from str[2] to ending
  8. wish [:4:] => accessing from 0th to 3 in steps of 1
  9. wish [-4: -1] => access -4 to -1

Note: If you are not specifying the beginning index, it will consider the beginning of the string. If you are not specifying the end index, it will consider the end of the string. The default value for the step is 1

Example: Slicing operator using several use cases (Demo11.py)
wish = "Hello World"
print(wish[::])
print(wish[:])
print(wish[0:9:1])
print(wish[0:9:2])
print(wish[2:4:1])
print(wish[::2])
print(wish[2::])
print(wish[:4:])
print(wish[-4:-1])
Output:

Slicing operator using several use cases in python

What is Immutable in Python?

Once we create an object, then the state of the existing object cannot be changed or modified. This behavior is called immutability. Once we create an object, then the state of the existing object can be changed or modified. This behavior is called mutability.

Strings are immutable in Python:

A string having an immutable nature. Once we create a string object, we cannot change or modify the existing object.

Example: Immutable (Demo12.py)
name = "Balayya"
print(name)
print(name[0])
name[0]="X"

Output: TypeError: ‘str’ object does not support item assignment

Mathematical operators on string objects in Python

We can perform two mathematical operators on a string. Those operators are:

  1. Addition (+) operator.
  2. Multiplication (*) operator.
Addition operator on strings in Python:

The + operator works like concatenation or joins the strings. While using the + operator on the string, then compulsory both arguments should be a string type. Otherwise, we will get an error.

Example: Concatenation (Demo13.py)
a = "Python"
b = "Programming"
print(a+b)

Output: Python Programming

Example: Concatenation (Demo14.py)
a = "Python"
b = 4
print(a+b)
Output:

Addition operator on strings in Python

Multiplication operator on Strings in Python:

This is used for string repetition. While using the * operator on the string, the compulsory one argument should be a string, and other arguments should be int type.

Example: Multiplication (Demo15.py)
a = "Python"
b = 3
print(a*b)

Output: PythonPythonPython

Example: Multiplication (Demo16.py)
a = "Python"
b = "3"
print(a*b)
Output:

Multiplication operator on Strings in Python

How do you find the length of a string in Python?

We can find the length of the string by using the len() function. Using the len() function, we can find groups of characters in a string. The len() function returns int as a result.

Example: len Function (Demo17.py)
course = "Python"
print("Length of string is:",len(course))

Output: Length of string is: 6

Membership Operators in Python:

We can check if a string or character is a member/substring of a string or not by using the below operators:

  1. In
  2. not in
in operator

in operator returns True if the string or character is found in the main string.

Example: in operator (Demo18.py)
print('p' in 'python')
print('z' in 'python')
print('on' in 'python')
print('pa' in 'python')
Output:

Membership Operators in Python

Example: To find a substring in the main string (Demo19.py)
main=input("Enter main string:")
s=input("Enter substring:")
if s in main:
   print(s, "is found in main string")
else:
   print(s, "is not found in main string")
Output1:

To find substring in the main string

Output2:

To find substring in the main string

Not in Operator in Python

The not-in operator returns the opposite result of an operator. not in operator returns True if the string or character is not found in the main string.

Example: not in operator (Demo20.py)
print(‘b’ not in ‘apple’)
Output: True

Comparing strings in Python:

We can use the relational operators like >, >=, <, <=, ==, != to compare two string objects. While comparing, it returns boolean values, either True or False. The comparison will be done based on alphabetical order or dictionary order.

Example: Comparison operators on the string in Python (Demo21.py)
s1 = "abcd"
s2 = "abcdefg"
print(s1 == s2)
if(s1 == s2):
   print("Both are same")
else:
   print("not same")
Output:

Comparison operators on the string in Python

Example: User name validation (Demo22.py)
user_name ="rahul"
name = input("Please enter user name:")
if user_name == name:
   print("Welcome to gmail: ", name)
else:
   print("Invalid user name, please try again")
Output:

Not in Operator in Python

How to remove spaces from a string in Python?

Space is also considered as a character inside a string. Sometimes, unnecessary spaces in a string will lead to wrong results.

Example: To check space importance in the string at the end of the string (Demo23.py)
s1 = "abcd"
s2 = "abcd    "
print(s1 == s2)
if(s1 == s2):
   print("Both are same")
else:
   print("not same")
Output:

Program To check space importance in the string at the end of the string in python

Predefined methods to remove spaces in Python
  1. rstrip() -> remove spaces at the right side of the string
  2. lstrip() -> remove spaces at the left side of the string
  3. strip() -> remove spaces at left & right sides of string

Note: These methods won’t remove the spaces which are in the middle of the string.

Example: To remove spaces in the start and end of the string in Python (Demo24.py)
course = "Python  "
print("with spaces course length is: ",len(course))
x=course.strip()
print("after removing spaces, course length is: ",len(x))
Output:

remove spaces in the star and end of the string in python

How do you find substrings in a string in python?

We can find a substring in two directions forwarding and backward direction. We can use the following 4 methods:

For forwarding direction
  1. find()
  2. index()
For backward direction
  1. rfind()
  2. rindex()
find() method:

Syntaxnameofthestring.find(substring)

This method returns an index of the first occurrence of the given substring. We will get a -1(minus one) value if it is unavailable. By default, the find() method can search the total string of the object. You can also specify the boundaries while searching.

Syntax – nameofthestring.find(substring, begin, end)

It will always search from the beginning index to the end-1 index.

Example: finding substring by using the find method in Python (Demo25.py)
course="Python programming language"
print(course.find("p"))
print(course.find("a", 1, 20))
Output:

finding substring by using find method in python

index() method in Python:

index() method is exactly the same as the find() method, except that if the specified substring is not available, then we will get ValueError. So, we can handle this error at the application level.

Example: finding substring by using index method (Demo26.py)
s="Python programming language"
print(s.index("Python"))

Output: 0

Example: finding substring by using index method (Demo27.py)
s="Python programming language"
print(s.index("Hello"))
Output:

String in Python with Examples

Example: Handling the error (Demo28.py)
s="Python programming language"
try:
   print(s.index("Hello"))
except ValueError:
   print("not found")

Output: not found

How to Count substrings in a given String in Python?

By using the count() method, we can find the number of occurrences of substring present in the string

Syntax – nameofthestring.count(substring)

Example: count() (Demo29.py)
s="Python programming language, Python is easy"
print(s.count("Python"))
print(s.count("Hello"))
Output:

How to Count substring in a given String in Python?

How to replace a string with another string in Python?

We can replace the old string with a new one using the replace() method. As we know, the string is immutable, so the replace() method never performs changes on the existing string object. The replace() method creates a new string object. We can check this by using the id() method.

Syntax- nameofthestring.replace(old string, new string)

Example: replace a string with another string (Demo30.py)
s1="Java programming language"
s2=s1.replace("Java", "Python")
print(s1)
print(s2)
print(id(s1))
print(id(s2))
Output:

How to replace a string with another string in Python?

Does the replace() method modify the string objects in Python?

A big NO. The string is immutable. Once we create a string object, we cannot change or modify the existing string object. This behavior is called immutability.

If you are trying to change or modify the existing string object, then a new string object will be created with those changes. So, replacing the () method will create a new string object with the modifications.

How to Split a string in Python?

We can split the given string according to the specified separator by using the split() method. The default separator is space. split() method returns a list.

Syntax- nameofthestring=s.split(separator)

Example: Splitting a string in Python (Demo31.py)
message="Python programming language"
n=message.split()
print("Before splitting: ",message)
print("After splitting: ",n)
print(type(n))
for x in n:
   print(x)
Output:

How to Split a string in Python?

Example: Splitting a string based on a separator in Python (Demo32.py)
message="Python programming language,Python is easy"
n=message.split(",")
print(n)
Output:

Splitting a string based on separator in python

How to Join strings in Python?

We can join a group of strings (list or tuple) with respect to the given separator.

Syntax: s=separator.join(group of strings)

Example: separator is – symbol joining string by using join() method (Demo33.py)
profile = ['Roshan', 'Actor', 'India']
candidate = '-'.join(profile)
print(profile)
print(candidate)
Output:

How to Join strings in Python?

Example: separator is : symbol joining string by using join() method (Demo34.py)
profile = ['Roshan', 'Actor', 'India']
candidate = ':'.join(profile)
print(profile)
print(candidate)
Output:

String in Python with Examples

How do you change cases of string in Python?
  1. upper() – This method converts all characters into upper case
  2. lower() – This method converts all characters into lowercase
  3. swapcase() – This method converts all lower-case characters to uppercase and all upper-case characters to lowercase
  4. title() – This method converts all characters to title case (The first character in every word will be in upper case, and all remaining characters will be in lower case)
  5. capitalize() – Only the first character will be converted to uppercase, and all remaining characters can be converted to lowercase.
Example: Changing cases (Demo35.py)
message='Python programming language'
print(message.upper())
print(message.lower())
print(message.swapcase())
print(message.title())
print(message.capitalize())
Output:

How to change cases of string in Python?

How to Formatting the Strings in Python?

We can format the strings with variable values by using the replacement operator {} and format() method.

Example: Formatting strings (Demo36.py)
name='Rakesh'
salary=100
age=16
print("{} 's salary is {} and his age is {}".format(name, salary, age))
print("{0} 's salary is {1} and his age is {2}".format(name, salary, age))
print("{x} 's salary is {y} and his age is{z}".format(z=age,y=salary,x=name))
Output:

How to Formatting the Strings in Python?

Character Data Type in Python:

If a single character stands alone, then we can say that it is a single character. For example: M -> Male F -> Female. In other programming languages, the char data type represents the character type, but in Python, no specific data type represents characters. We can fulfill this requirement by taking a single character in single quotes. A single character also represents a string type in Python.

Example: Character data type (Demo37.py)
gender1 = "M"
gender2 = "F"
print(gender1)
print(gender2)
print(type(gender1))
print(type(gender2))
Output:

Strings in Python with Examples

In the next article, I am going to discuss Functions in Python. In this article, I try to explain strings in Python with examples. I hope you enjoy this Strings in Python with Examples article. I would like to have your feedback. Please post your feedback, questions, or comments about this article.

Leave a Reply

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