1 of 70

STRINGS

2 of 70

String Literals: A string is a group of characters. String literals in python are surrounded by either single quotation marks, and double quotation marks or triple quotes.

'hello' is the same as "hello“ and “””hello”””

Assign String to a Variable: Assigning a string to a variable is done with the variable name followed by an equal sign and the string.

Example

a = "Hello"�print(a)

Multiline Strings: You can assign a multiline string to a variable by using three quotes.

Example

a = ""“This is python programming and

very popular language in now a days."""�print(a)

Or

a =‘’’This is python programming and

very popular language in now a days.’’’�print(a)

3 of 70

4 of 70

Accessing Values in Strings:

  • Python does not support a character type; these are treated as strings of length one, thus also considered a substring.
  • To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. For example −

Example:

var1="hello“

var2="how are you“

print("var1 is",var1)

print("var2 is",var2)

Output:

var1 is hello

var2 is how are you

5 of 70

6 of 70

7 of 70

8 of 70

Updating Strings:

You can "update" an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether.

Example:

var1='Hello World!'

print("Updated String :- ", var1[:6] + 'Python')

print(var1)

Output:

Updated String :- Hello Python

Hello World!

9 of 70

Slicing: You can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string.

Example-1:

#Get the characters from position 2 to position 5 (not included):

b = "Hello, World!“

print(b[2:5])

Output:

llo

Example-2:

#print the string in reverse order

print(a[::-1])

Output:

olleh

10 of 70

Escape Characters:

  • To insert characters that are illegal in a string, use an escape character.
  • An escape character is a backslash \ followed by the character you want to insert.
  • An example of an illegal character is a double quote inside a string that is surrounded by double quotes:

Example: You will get an error if you use double quotes inside a string that is surrounded by double quotes:

txt = "We are the so-called "Vikings" from the north."

If you execute the above code it shows error, because you placed “Vikings” in txt illegally.To fix this problem, use the escape character \":

Example

The escape character allows you to use double quotes when you normally would not be allowed:

txt = "We are the so-called \"Vikings\" from the north."

11 of 70

Code

Result

\'

Single Quote

\\

Backslash

\n

New Line

\r

Carriage Return

\t

Tab

\b

Backspace

\ooo

Octal value

\xhh

Hex value

Other escape characters used in Python:

12 of 70

Example:

print("Single Quote escape character: ","Hello\'world\'")

print("Double Quote escape character: ","Hello\"world\"")

print("Back Slash escape character: ","Hello\\world")

print("New Line escape character: ","Hello\nworld")

print("Carriage Return escape character: ","Hello\rWorld")

print("Tab escape character: ","Hello\tworld")

print("Back Space escape character: ","Hello\bworld")

print("Octal escape character: ","\110\145\154\154\157")

print("Hexa-decimal escape character: ","\x48\x65\x6c\x6c\x6f")

Output:

Single Quote escape character: Hello'world'

Double Quote escape character: Hello"world"

Back Slash escape character: Hello\world

New Line escape character: Hello world

Worldage Return escape character: Hello

Tab escape character: Hello world

Back Space escape character: Hellworld

Octal escape character: Hello

Hexa-decimal escape character: Hello

13 of 70

String Special Operators

Assume string variable a holds 'Hello' and variable b holds 'Python', then −

14 of 70

Example:

a="Hello"

b="Python"

print(a+b) #Concatenation of a and b

print(a*3) #displays a 3 times

print(a[2]) #displays the 2 index element in a

print(a[1:4]) #displays the characters from 1 to 4 except 4th index

print('H'in a)

print('H'not in a)

Output:

HelloPython

HelloHelloHello

l

ell

True

False

15 of 70

16 of 70

17 of 70

18 of 70

  • A Python raw string is a normal string, prefixed with a r or R.
  • This treats characters such as backslash (‘\’) as a literal character. This also means that this character will not be treated as a escape character.
  • To understand what a raw string exactly means, let’s consider the below string, having the sequence “\n”.

Example:

s=print(“Hello\tfrom\nlbrce”)

print(s)

Output:

Hello from

lbrce

  • Applying raw string concept for above example.

Example:

s=print(r“Hello\tfrom\nlbrce”)

print(s)

Output:

Hello\tfrom\nlbrce

19 of 70

  • Raw string concept generally used in a case there python strings will not work

Example:

s=“Hello Every\xone”

print(s)

Output:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 11-12: truncated \xXX escape

  • The above code shows an error because we placed \x illegally in s.
  • To avoid the such type of errors we should use raw string concept.

Example:

s=r“Hello Every\xone”

print(s)

Output:

'Hello Every\\xone'

20 of 70

Unicode Strings:

  • Basically a string is a group of characters.
  • Every character is having it’s corresponding decimal number(ASCII).
  • ASCII Character set provides decimal values for only 128 character-set.
  • Extended ASCII Character set provides decimal values for 256 character-set.
  • But in universe we are having lot of symbols like Latin-script alphabets, Greek, Armenian, Arabic…
  • In order to represent all the symbols in the universe python uses UNICODE standard, where as other programming languages like C, C++, Java follows ASCII standard.
  • In Python 2.7 to represent Unicode character we should use \u escape sequence but in python3.0 no need to use that escape sequence.

21 of 70

Method

Description

capitalize()

Converts the first character to upper case

casefold()

Converts string into lower case

center()

Returns a cantered string

count()

Returns the number of times a specified value occurs in a string

encode()

Returns an encoded version of the string

endswith()

Returns true if the string ends with the specified value

expandtabs()

Sets the tab size of the string

find()

Searches the string for a specified value and returns the position of where it was found

format()

Formats specified values in a string

format_map()

Formats specified values in a string

22 of 70

Searches the string for a specified value and returns the position of where it was found

Returns True if all characters in the string are alphanumeric

Returns True if all characters in the string are in the alphabet

Returns True if all characters in the string are decimals

Returns True if all characters in the string are digits

Returns True if the string is an identifier

Returns True if all characters in the string are lower case

Returns True if all characters in the string are numeric

Returns True if all characters in the string are printable

Returns True if all characters in the string are whitespaces

Returns True if the string follows the rules of a title

Returns True if all characters in the string are upper case

23 of 70

Joins the elements of an iterable to the end of the string

Returns a left justified version of the string

Converts a string into lower case

Returns a left trim version of the string

Returns a translation table to be used in translations

Returns a tuple where the string is parted into three parts

Returns a string where a specified value is replaced with a specified value

Searches the string for a specified value and returns the last position of where it was found

Searches the string for a specified value and returns the last position of where it was found

Returns a right justified version of the string

Returns a tuple where the string is parted into three parts

Splits the string at the specified separator, and returns a list

Returns a right trim version of the string

24 of 70

Splits the string at the specified separator, and returns a list

Splits the string at line breaks and returns a list

Returns true if the string starts with the specified value

Returns a trimmed version of the string

Swaps cases, lower case becomes upper case and vice versa

Converts the first character of each word to upper case

Returns a translated string

Converts a string into upper case

Fills the string with a specified number of 0 values at the beginning

25 of 70

1.capitalize(): The capitalize() method returns a string where the first character is upper case.

Syntax: string_variable.capitalize()

Parameters: No Parameters

Example:

s=“python programming”

s.capitalize()

Output: Python programming

2.casefold(): The casefold() method returns a string where all the characters are lower case. This method is similar to the lower() method, but the casefold() method is stronger, more aggressive, meaning that it will convert more characters into lower case, and will find more matches when comparing two strings and both are converted using the casefold() method.

Syntax: string_variable.casefold()

Parameters: No Parameters

Example:

s=“PYTHON PROGRAMMING”

s.casefold()

Output: python programming

26 of 70

3. center(): The center() method will center align the string, using a specified character (space is default) as the fill character.

Syntax: string.center(length, character)

Parameter Values:

Parameter

Description

length

Required. The length of the returned string

character

Optional. The character to fill the missing space on each side. Default is " " (space)

Example:

txt = "banana"

x = txt.center(20, "O")

print(x)

Output: OOOOOOObananaOOOOOOO

27 of 70

4. count(): The count() method returns the number of times a specified value appears in the string.

Syntax: string.count(value, start, end)

Parameters:

Parameter

Description

value

Required. A String. The string to value to search for

start

Optional. An Integer. The position to start the search. Default is 0

end

Optional. An Integer. The position to end the search. Default is the end of the string

Example:

txt = "I love apples, apple are my favorite fruit"

x = txt.count("apple")

print(x)

Output: 2

28 of 70

5. encode(): The encode() method encodes the string, using the specified encoding. If no encoding is specified, UTF-8 will be used.

Syntax: string.encode(encoding=encoding, errors=errors)

Parameters:

Parameter

Description

encoding

Optional. A String specifying the encoding to use. Default is UTF-8

errors

Optional. A String specifying the error method. Legal values are:�

'backslashreplace'

- uses a backslash instead of the character that could not be encoded

'ignore'

- ignores the characters that cannot be encoded

'namereplace'

- replaces the character with a text explaining the character

'strict'

- Default, raises an error on failure

'replace'

- replaces the character with a questionmark

'xmlcharrefreplace'

- replaces the character with an xml character

29 of 70

Example:

txt = "My name is Ståle"

print(txt.encode(encoding="ascii",errors="backslashreplace"))

print(txt.encode(encoding="ascii",errors="ignore"))

print(txt.encode(encoding="ascii",errors="namereplace"))

print(txt.encode(encoding="ascii",errors="replace"))

print(txt.encode(encoding="ascii",errors="xmlcharrefreplace"))

Output:

b'My name is St\\xe5le'b'My name is Stle'b'My name is St\\N{LATIN SMALL LETTER A WITH RING ABOVE}le'b'My name is St?le'b'My name is Ståle'

6. endswith(): The endswith() method returns True if the string ends with the specified value, otherwise False.

Syntax: string.endswith(value, start, end)

30 of 70

Parameter

Description

value

Required. The value to check if the string ends with

start

Optional. An Integer specifying at which position to start the search

end

Optional. An Integer specifying at which position to end the search

Parameter Values

Example:

txt = "Hello, welcome to my world."

x = txt.endswith("my world.")

print(x)

Output: True

31 of 70

7. expandtabs(): The expandtabs() method sets the tab size to the specified number of whitespaces.

Syntax: string.expandtabs(tabsize)

Parameter: tabsize (optional). A number specifying the tabsize. Default tabsize is 8

Example:

txt = "H\t\te\tl\tl\to"

print(txt)

print(txt.expandtabs())

print(txt.expandtabs(2))

print(txt.expandtabs(4))

print(txt.expandtabs(10))

Output:

H e l l o

H e l l o

H e l l o

H e l l o

H e l l o

H e l l o H e l l o H e l l o H e l l o H e l l o

32 of 70

8. find():

  • The find() method finds the first occurrence of the specified value.
  • The find() method returns -1 if the value is not found.
  • The find() method is almost the same as the index() method, the only difference is that the index() method raises an exception if the value is not found.

Syntax: string.find(value, start, end)

Parameters:

Parameter

Description

value

Required. The value to search for

start

Optional. Where to start the search. Default is 0

end

Optional. Where to end the search. Default is to the end of the string

33 of 70

9. index:

The index() method finds the first occurrence of the specified value.

The index() method raises an exception if the value is not found.

The index() method is almost the same as the find() method, the only difference is that the find() method returns -1 if the value is not found. 

Syntax: string.find(value, start, end)

Parameters:

Parameter

Description

value

Required. The value to search for

start

Optional. Where to start the search. Default is 0

end

Optional. Where to end the search. Default is to the end of the string

Example-1: 

txt = "Hello, welcome to my world."

x = txt.find("e")

print(x)

Output: 1

Example-2: 

txt = "Hello, welcome to my world."

x = txt.find(“a")

print(x)

Output: -1

34 of 70

10. isalnum(): The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).

Syntax: string.isalnum()

Parameters: No-parameters

Example:

txt = "Company 12"

x = txt.isalnum()

print(x)

Output: False

11. isalpha(): The isalpha() method returns True if all the characters are alphabet letters (a-z).

Syntax: string.isalpha()

Parameters: No-parameters

Example:

txt = "Company 12"

x = txt.isalpha()

print(x)

Output: False

35 of 70

12. isdecimal(): The isdecimal() method returns True if all the characters are decimals (0-9).

Syntax: string.isdecimal()

Parameters: No-parameters

Example:

a = "\u0030" #unicode for 0

b = "\u0047" #unicode for G

print(a.isdecimal())

print(b.isdecimal())

Output: True, False

13. isdigit(): The isdigit() method returns True if all the characters are digits, otherwise False.

Syntax: string.isdigit()

Parameters: No-parameters

Example:

txt = "50800“

x = txt.isdigit()

print(x)

Output:

True

36 of 70

14. isidentifier(): The isidentifier() method returns True if the string is a valid identifier, otherwise False.

A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-9), or underscores (_). A valid identifier cannot start with a number, or contain any spaces

Syntax: string.isidentifier()

Parameters: No-parameters

Example:

a = "MyFolder"

b = "Demo002"

c = "2bring"

d = "my demo"

print(a.isidentifier())

print(b.isidentifier())

print(c.isidentifier())

print(d.isidentifier())

Output:

True�True�False�False

.

37 of 70

15. islower()/isupper: The islower() method returns True if all the characters are in lower case, otherwise False. Numbers, symbols and spaces are not checked, only alphabet characters.

Syntax: string.islower()

Parameters: No-parameters

Example:

a = "Hello world!"

b = "hello 123"

print(a.islower())

print(b.islower())

Output: False, True

16. isprintable(): The isprintable() method returns True if all the characters are printable, otherwise False. Example of none printable character can be carriage return and line feed.

Syntax: string.isprintable()

Parameters: No-parameters

Example:

txt = "Hello!\nAre you #1?"

x = txt.isprintable()

print(x)

Output:

False

38 of 70

17. isspace(): The isspace() method returns True if all the characters in a string are whitespaces, otherwise False.

Syntax: string.isspace()

Parameters: No-parameters

Example:

a = “ kl !"

print(a.isspace())

Output: False

18. istitle(): The istitle() method returns True if all words in a text start with a upper case letter, AND the rest of the word are lower case letters, otherwise False. Symbols and numbers are ignored.

Syntax: string.istitle()

Parameters: No-parameters

Example: a = "HELLO, AND WELCOME TO MY WORLD"

b = "Hello"

c = "This Is %'!?"

print(a.istitle())

print(b.istitle())

print(c.istitle())

39 of 70

19. isspace(): The isspace() method returns True if all the characters in a string are whitespaces, otherwise False.

Syntax: string.isspace()

Parameters: No-parameters

Example:

a = “ kl !"

print(a.isspace())

Output: False

20. join(): The join() method takes all items in an iterable and joins them into one string. A string must be specified as the separator.

Syntax: string.join(iterable)

Parameters: iterable-Required Any iterable object where all the returned values are strings

Example:

myTuple = ("John", "Peter", "Vicky")

x = "#".join(myTuple)

print(x)

Output:

John#Peter#Vicky

40 of 70

41 of 70

TUPLES

42 of 70

43 of 70

44 of 70

45 of 70

46 of 70

47 of 70

48 of 70

49 of 70

50 of 70

51 of 70

52 of 70

53 of 70

sets

54 of 70

SETS in Python

55 of 70

56 of 70

57 of 70

58 of 70

59 of 70

DICTIONARIES

60 of 70

61 of 70

62 of 70

63 of 70

64 of 70

65 of 70

66 of 70

67 of 70

68 of 70

69 of 70

70 of 70