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.
# string with single quotesmy_string = 'Welcome'print(my_string)# string with double quotesmy_string = "Welcome I’m in Strings"print(my_string)# string with triple quotesmy_string = '''Welcome'''print(my_string)
indexing
or a range of characters using slicing
.0
.IndexError
.integer
.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 Pythonstr1 = 'Computer'print('str1 = ', str1)#string are immutable# str1[0] ='c'#first characterprint('str1[0] = ', str1[0])#last characterprint('str1[-1] = ', str1[-1])#index Error#print('str1[-1] =', str1[9])#slicing 2nd to 5th characterprint('str1[3:5] = ', str1[3:5])#slicing can be done by slice functionx=slice(3,5)print('str1[3,5]= ', str1[x])#slicing 6th to 2nd last characterprint('str1[5:-2] = ', str1[5:-2])
There are many operations that can be performed with strings.
+
operator will be used to concatenate in Python.*
operator can be used to repeat the string for a given number of times.# Python String Operationsstr1 ='Computer'str2 ='Science'# using +print('str1 + str2 = ', str1 + str2)# using *print('str1 * 3 =', str1 * 3)
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 stringname ="welcome"for letter in name:print("Letter is "+letter)
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