Basics of strings in Python

A String is a sequence of characters, which means it is an ordered collection of other values.

Python strings are immutable, meaning that they cannot be changed after they are created.

The Various String Real-Time Applications in Python are:

  • Natural language Processing
  • Regular expression
  • Data mining
  • Dictionaries
  • Chatbot
  • Machine translation

How to create a string in Python

  • Strings can be created by enclosing characters inside single quotes or double-quotes.
  • Triple quotes can also be used in Python, but are generally used to represent multi-line strings and docstrings.

Code

# string with single quotes
my_string = 'Welcome'
print(my_string)
# string with double quotes
my_string = "Welcome I’m in Strings"
print(my_string)
# string with triple quotes
my_string = '''Welcome'''
print(my_string)

Indexing in Strings

  • We can access individual characters using indexing or a range of characters using slicing.
  • Index will always start from 0.
  • Trying to access a character out of index range will raise an IndexError.
  • The index must be an integer.
svg viewer

Accessing Values in String

To access each value or sub-string, use the square brackets to slice along the index or indices to obtain your sub-string.

#Accessing string characters in Python
str1 = 'Computer'
print('str1 = ', str1)
#string are immutable
# str1[0] ='c'
#first character
print('str1[0] = ', str1[0])
#last character
print('str1[-1] = ', str1[-1])
#index Error
#print('str1[-1] =', str1[9])
#slicing 2nd to 5th character
print('str1[3:5] = ', str1[3:5])
#slicing can be done by slice function
x=slice(3,5)
print('str1[3,5]= ', str1[x])
#slicing 6th to 2nd last character
print('str1[5:-2] = ', str1[5:-2])

Python String Operations

There are many operations that can be performed with strings.

a) Concatenation of Two or More Strings

  • Joining two or more strings into a single string is called concatenation.
  • The + operator will be used to concatenate in Python.
  • The * operator can be used to repeat the string for a given number of times.
# Python String Operations
str1 ='Computer'
str2 ='Science'
# using +
print('str1 + str2 = ', str1 + str2)
# using *
print('str1 * 3 =', str1 * 3)

b) Iterating through a string

We can iterate through a string using a for loop.

Below is an example of how to display the letter in a string:

# Iterating through a string
name ="welcome"
for letter in name:
print("Letter is "+letter)

Some Important String Functions

function Description
upper() We can convert a string to uppercase in Python using the str.upper() function
lower() We can convert a string to lowecase in Python using the str.lower() function
len() This function will return length of the String.
find() The Python String find() method is used to find the index of a substring in a string.
strip() Used to trim whitespaces from the string object.

Free Resources

Attributions:
  1. undefined by undefined