Strings in Python

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

Strings in Python

• Strings are the collection of characters or sequence of Unicode characters.


• Strings are the sequential data type in python like list and tuples.
• String is immutable in nature.
• String enclosed in single quotes or double quotes in Python.
• String can be enclosed in triple quotes also, generally it is used to represent
multiline strings.
• Python does not have a ‘char’ data type to store single character.
• Python consider a single character as a string only.
• String can accessible using square [] brackets.

How to create a string?


# Example of string
my_st = 'Python'
print(f'vlaue of st variable is {st}')
print(type( t)) # can check data type

# String operators
concatenate (+): we can concatenate two or more strings using plus (+)
operator
'Python' + 'Language' # 'PythonLanguage'
'55' + '65' # '5565'
replication (*): It performs replication instead of multiplication. The * operator
when used with numbers, it does multiplication and if we used with string and
integer, the i* operator replicate the string with given number of times.
'python'*3 # 'pythonpythonpython'
3 * '@Hello' #'@Hello@Hello@Hello'

Membership Operator: Python have two types of membership operators


• in: returns True, if character or substring exists in the specified string.
lang = 'python language'
'py' in lang will give True
'pt' in lang will give False
• not in: returns True, if character or substring does not exist in the specified
string.
lang = 'python language'
'py' not in lang will give False
'pt' not in lang will give True
'lang' in lang will give True
'on' in lang will give True

Comparison Operator:
All the relational operator works with strings for comparing strings together.
'python' == 'python' will give True
'python' == 'Python' will give False
Example:
str1 = input('Enter the first string: ')
str2 = input('Enter the second the string: ')
if str1 == str2:
print('Both strings are equal')
else:
print('Both strings are not equal')

Note: But to compare string for less than or greater than, comparison done on the
basis of ASCII or Unicode values.
Characters Ordinal Values

‘0’ to ‘9’ 48 to 57

‘A’ to ‘Z’ 65 to 90

‘a’ to ‘z’ 97 to 122

'java' < 'python'will give True


How? we can check by finding their ACII or Unicode values
ord('j') 106
ord('p') 112
that’s why ‘java’ is less than ‘python’
How we can access individual character or substring from a string
• We can access single character from string using Indexing.
• We can access substring from a string using slice operator [] that is known
as slicing.
• To access single character, need to pass index in square brackets.
• To access substring, need to pass indexes or indices in square brackets

sample = 'amazing python'


sample[5] ' n'

sample[7] ''

sample[13] ' n'

sample[14] Error, out of range

sample[-1] ' n'

sample[-5] 'y'

For fetching range of characters using indices:


string [start: end: step]
Note:
start is optional, if not mentioned then its default value is 0.
end, is also optional, if not mentioned the will display all the characters,
otherwise it would be n-1, means display character with one index
less than the given value of end.
step, is also optional, default value is +1 and could be negative also.

sample = 'amazing python'


'mazi'
sample[1:5]
'ng pytho'
sample[5:13]
'ing python'
sample[4: ]
'amazing py'
sample[:10]
'amazing python'
sample[ : ]
'azing pyt'
sample[2:-3]
''
sample[-2:3]
'ing p'
sample[-10:-5]
''
sample[-5:-10]
'aigp'
sample[2:10:2]

String (built-in) function and methods


# len(): It returns the length of the string
length = len(sample) # 14
---------------------------------------------------------------
# capitalize(): returns a copy of the string with its first letter capitalized.
mystr = 'python is a programming language'
print(mystr.capitalize())
Python is a programming language
------------------------------------------------------------------
# find(): It's find the substring in the given string and gives lowest index within
indices
mystr = 'python is a programming language'
print(mystr.find('is')) # 7
print(mystr.find('is',2,10)) # 7
print(mystr.find('is',2,5)) # -1, gives -1 if not found
------------------------------------------------------------------------------------------
# isalnum(): It returns True if string contains alphanumeric (alphabets or
number).
mystr = 'Python123'
mystr.isalnum() will give True
mystr = 'Python'
mystr.isalnum() will give True

mystr = '123'
mystr.isalnum() will give True

mystr = ''
mystr.isalnum() will give False
------------------------------------------------------------------------------
# isalpha(): It returns True if all the characters are alphabetic
mystr = 'python'
mystr.isalpha() will give True

mystr = 'python12'
mystr.isalpha() will give False

mystr = '123'
mystr.isalpha() will give False
--------------------------------------------------------------------------------
# isdigit(): It returns True if all the characters are digits.
mystr = '123'
mystr.isdigit() will give True

mystr = 'python123'
mystr.isdigit() will give False
----------------------------------------------------------------------------------
# islower(): It returns True if all the characters are in lower case.
mystr = 'python'
mystr.islower() will give True
mystr = 'Python'
mystr.islower() will give False

mystr = 'PYTHON'
mystr.islower() will give False

mystr = ''
mystr.islower() will give False
--------------------------------------------------------------------------------------------
# isspace(): It returns True if there are only whitespaces.
mystr = ' '
mystr.isspace() will give True

mystr = ' '


mystr.isspace() will give False
---------------------------------------------------------------------------------------------
# isupper(): It reurns True if all the characters are in uppercase.
mystr = 'PYTHON'
mystr.isupper() will give True

mystr = 'Python'
mystr.isupper() will give False
mystr = 'P123'
mystr.isupper() will give True

mystr = 'P P'


mystr.isupper() will give True

mystr = 'P___'
mystr.isupper() will give True
-----------------------------------------------------------------------------------------
# lower(): converts string in lowercase.
mystr ='PYTHON'
mystr.lower() will give 'python'
------------------------------------------------------------------------------------------
# upper(): converts string in uppercase.
mystr ='python'
mystr.upper() will give 'PYTHON'
-------------------------------------------------------------------------------------------
# lstrip(): It removes the leading characters and returns the string
# if whitespaces are there, then it will be removed too
mystr = ' Python'
mystr.lstrip() will give 'Python'
mystr = 'Python'
mystr.lstrip('P') will give 'ython'

mystr = '@@@Python@@'
mystr.lstrip('@') will give 'Python@@'
mystr = '@@@Python@@'
mystr.lstrip('th') will give '@@@Python@@'
mystr = 'Pythob'
mystr.lstrip('tyP') will give 'hob'
---------------------------------------------------------------------------------------------------------

# rstrip(): It removes the trailing characters and returns the string


# if whitespaces are there, then it will be removed too
mystr = 'Python123'
mystr.rstrip('123') will give 'Python'

mystr = 'Python'
mystr.rstrip('on') will give 'Pyth'

mystr = '$Python$$'
mystr.rstrip('$')
---------------------------------------------------------------------------------------------
# strip(): It returns the leading and trailing whitespaces around string or matching
substring.
mystr = '@@@Python@@'
print(mystr.strip('@')) will give Python

----------------------------------------------------------------------------------------------
# count(): It returns the number of occurrences of the substring in a string.
mystr = 'Python is best for AI and Ml. Python is best for Games too'
mystr.count('best') #2
------------------------------------------------------------------------------------------------
# index():It returns the lowest index, where substring is found.
mystr = 'Python is the most amazing language'
print(mystr.index('most')) # 14
--------------------------------------------------------------------------------------------------

# replace(): It replaces all the occurrences of matching substring to new string.


mystr = 'It is the most amazing language and It supports AI too'
print(mystr.replace('It','Python'))
Python is the most amazing language and Python supports AI too
---------------------------------------------------------------------------------------------------

# title(): It returns the string in title case.


mystr ='python was developed by guvido van rossum'
print(mystr.title())
Python Was Developed By Guvido Van Rossum
Note: istitle() function returns True, if the string is in title case
----------------------------------------------------------------------------------------------------

# join(): It joins a string or character after each character of the string iterator.
'-'.join('Hello')
'H-e-l-l-o'
------------------------------------------------------------------------------------------------------
# split(): It splits the string on the basis of given string or character and returns as
a list of string.
mystr = 'python was developed by Guido Van Rossum'
mystr.split() # by default it splits with space.
['python', 'was', 'developed', 'by', 'Guido', 'Van', 'Rossum']
-------------------------------------------------------------------------------------------------------

You might also like