Python String
Python string is the collection of the characters surrounded by single quotes, double quotes, or
triple quotes.
#Using single quotes
str1 = 'Hello Python'
print(str1)
#Using double quotes
str2 = "Hello Python"
print(str2)
#Using triple quotes
str3 = '''''Triple quotes are generally used for
represent the multiline or
docstring'''
print(str3)
Strings indexing and splitting
Like other languages, the indexing of the Python strings starts from 0. For example, The string
"HELLO" is indexed as given in the below figure.
with negative indexing
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string object
doesn't support item assignment i.e., A string can only be replaced with new string since its content
cannot be partially replaced.
# This will give your error
str = "HELLO"
str[0] = "h"
But you can do
str = "HELLO"
str = "hello"
Deleting the String
As we know that strings are immutable. We cannot delete or remove the characters from the string.
But we can delete the entire string using the del keyword.
This will be an error
str = "CUTM"
del str[1]
This will work
str1 = "CUTM"
del str1
String Operators
Operator Description
+ It is known as concatenation operator used to join the strings given either side of the operator.
* It is known as repetition operator. It concatenates the multiple copies of the same string.
[] It is known as slice operator. It is used to access the sub-strings of a particular string.
[:] It is known as range slice operator. It is used to access the characters from the specified range.
It is known as membership operator. It returns if a particular sub-string is present in the specified
in
string.
It is also a membership operator and does the exact reverse of in. It returns true if a particular
not in
substring is not present in the specified string.
It is used to specify the raw string. Raw strings are used in the cases where we need to print the actual
r/R meaning of escape characters such as "C://python". To define any string as a raw string, the character r
or R is followed by the string.
It is used to perform string formatting. It makes use of the format specifiers used in C programming
%
like %d or %f to map their values in python. We will discuss how formatting is done in python.
In [ ]:
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
The list of an escape sequence
Sr. Escape Sequence Description
1. \newline It ignores the new line.
2. \ Backslash
3. \' Single Quotes
4. \'' Double Quotes
5. \a ASCII Bell
6. \b ASCII Backspace(BS)
7. \f ASCII Formfeed
8. \n ASCII Linefeed
9. \r ASCII Carriege Return(CR)
10. \t ASCII Horizontal Tab
11. \v ASCII Vertical Tab
12. \ooo Character with octal value
13 \xHH Character with hex value.
In [ ]:
print("C:\\Users\\DEVANSH SHARMA\\Python32\\Lib")
print("This is the \n multiline quotes")
print("This is \x48\x45\x58 representation")
C:\Users\DEVANSH SHARMA\Python32\Lib
This is the
multiline quotes
This is HEX representation
In [ ]:
# Using Curly braces
print("{} and {} both are the best friend".format("Devansh","Abhishek"))
#Positional Argument
print("{1} and {0} best players ".format("Virat","Rohit"))
#Keyword Argument
print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))
Devansh and Abhishek both are the best friend
Rohit and Virat best players
James,Peter,Ricky
In [ ]:
Integer = 10;
Float = 1.290
String = "Devansh"
print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am st
Hi I am Integer ... My value is 10
Hi I am float ... My value is 1.290000
Hi I am string ... My value is Devansh
Method Description
It capitalizes the first character of the String. This function is deprecated in
capitalize()
python3
casefold() It returns a version of s suitable for case-less comparisons.
It returns a space padded string with the original string centred with equal number
center(width ,fillchar)
of left and right spaces.
It counts the number of occurrences of a substring in a String between begin and
count(string,begin,end)
end index.
decode(encoding = 'UTF8',
Decodes the string using codec registered for encoding.
errors = 'strict')
encode() Encode S using the codec registered for encoding. Default encoding is 'utf-8'.
endswith(suffix It returns a Boolean value if the string terminates with given suffix between begin
,begin=0,end=len(string)) and end.
expandtabs(tabsize = 8) It defines tabs in string to multiple spaces. The default space value is 8.
find(substring ,beginIndex, It returns the index value of the string where substring is found between begin
endIndex) index and end index.
format(value) It returns a formatted version of S, using the passed value.
index(subsring, beginIndex,
It throws an exception if string is not found. It works same as find() method.
endIndex)
It returns true if the characters in the string are alphanumeric i.e., alphabets or
isalnum()
numbers and there is at least 1 character. Otherwise, it returns false.
It returns true if all the characters are alphabets and there is at least one character,
isalpha()
otherwise False.
isdecimal() It returns true if all the characters of the string are decimals.
It returns true if all the characters are digits and there is at least one character,
isdigit()
otherwise False.
isidentifier() It returns true if the string is the valid identifier.
islower() It returns true if the characters of a string are in lower case, otherwise false.
isnumeric() It returns true if the string contains only numeric characters.
Method Description
isprintable() It returns true if all the characters of s are printable or s is empty, false otherwise.
isupper() It returns false if characters of a string are in Upper case, otherwise False.
isspace() It returns true if the characters of a string are white-space, otherwise false.
It returns true if the string is titled properly and false otherwise. A title string is the
istitle() one in which the first character is upper-case whereas the other characters are
lower-case.
It returns true if all the characters of the string(if exists) is true otherwise it returns
isupper()
false.
join(seq) It merges the strings representation of the given sequence.
len(string) It returns the length of a string.
lower() It converts all the characters of a string to Lower case.
It removes all leading whitespaces of a string and can also be used to remove
lstrip()
particular character from leading.
It replaces the old sequence of characters with the new sequence. The max
replace(old,new[,count])
characters are replaced if max is given.
rfind(str,beg=0,end=len(str)) It is similar to find but it traverses the string in backward direction.
rindex(str,beg=0,end=len(str)) It is same as index but it traverses the string in backward direction.
Returns a space padded string having original string right justified to the number
rjust(width,[,fillchar])
of characters specified.
swapcase() It inverts case of all characters in a string.
It is used to convert the string into the title-case i.e., The string meEruT will be
title()
converted to Meerut.
upper() It converts all the characters of a string to Upper Case.