A collection of characters or alphabets are called a String. It contains special characters and also numbers written in quotes.

Strings are an immutable data type.

How to Declare Python String?

You can declare a string using either single quotes or double-quotes. Whenever we are taking input (using input()) any value from the user is taken as a string.

a = "Hello"
print (a)

[out: ]
Hello

b = 'World'
print (b)

[out: ]
World

If you want something in multiple lines, you can use a triple quote.

a = """Hii
How are you?"""

print (a)

[out: ] 
Hii
How are you?

How to Access Python String?

One can use indexing to access the elements of the string.
Slicing can be used to access the part of the string.

The index always starts from 0.

  • Positive Indexing : Reads from left to right, starts with 0 and ends with N-1
  • Negative Indexing : Reads from right to left, starts from end -1 and ends at -N, which is first element.
a = "Dog"
print (a[1])
print (a[-1])

[out: ]
o
g

The basic structure for Slicing

[start : end : iterator]
  1. Index starts at 0 and ends at the length of value.
  2. In slicing always start from the start and go till one index less than the given index position.
  3. Slicing is used in order to access the group of words.
  • st[1:4] :: It prints elements from index 1 to 3.
st = "Hello World"
print (st[1:4])

[out: ]
ell
  • st[1:] :: It prints elements from index 1 to the end of the string.
st = "Hello World"
print (st[1:])

[out: ]
ello World
  • st[:10] :: It prints elements from starting index that is 0 to 9.
st = "Hello World"
print (st[:10])

[out: ]
Hello Worl
  • st[-5:-1] :: It prints elements from index -3 to -2.
st = "Hello World"
print (st[-5:-1])

[out: ]
Worl
  • st[:] :: It prints all elements.
st = "Hello World"
print (st[:])

[out: ]
Hello World
  • st[1:8:2] :: It prints elements from index 1 to index 8 but only 2nd value.
st = "Hello World"
print (st[1:8:2])

[out: ]
el o

String Concatenation

It can be done by using “+”.

str1 = "Hi_"
str2 = "There"

str3 = str1 + str2
print (str3)

[out: ]
Hi_There

String Formatters

  • Sometimes, you may want to print variables along with a string. You can either use commas or use string for matters for the same.
name = "Parsis"
address = "India"
print("Name:",name,"Address:",address) 
print("Name:"+name+" Address:"+address)

[out: ]
Name: Parsis Address: India
Name:Parsis Address:India
  • f-string [Format Specifier for String]
name = 'Parsis'
print(f"It isn't {name}'s birthday")

[out: ]
It isn't Parsis's birthday
  • format() method
a = "Python"
print("{0} is awesome ".format(a))
print("{a} is awesome ".format(a="P"))

[out: ]
Python is awesome 
P is awesome 

For more than one value:

a = "Python"
b = "awesome"

print("{0} is {1} ".format(a,b))
print("{a} is {b} ".format(a="P", b="a"))

[out: ]
Python is awesome 
P is a 
  • % operator
    • The % operator goes where the variables go in a string.
    • %s :: string
    • %f :: float
    • %d :: int
a = "Wednesday"
b = "Python"

print("Today is %s and we have %s session." %(a,b))

[out: ]
Today is Wednesday and we have Python session.
 

Escape Sequences

  • In a Python string, you may want to put a tab, a linefeed, or other such things.
  • An escape sequence is a backslash followed by a character, depending on what you want to do.
  • Python supports the following sequences.
    • \n :: linefeed
    • \t :: tab [Creates 4 space]
    • \\ :: backslash
    • \’ :: A single quote can be escaped by a backslash.
    • \” :: Like the single quote, the double quote can be escaped too.
a = "Hi\nHello"
print (a)

[out: ]
Hi
Hello
a = "Hi\\Hello"
print (a)

[out: ]
Hi\Hello
a = "Hi\"Hello"
print (a)

[out: ]
Hi"Hello
a = "Hi\tHello"
print (a)

[out: ]
Hi Hello
a = "Hi\'Hello"
print (a)

[out: ]
Hi'Hello

String Functions

  • len() :: It returns the length of a string.
st = "Parsis"
print (len(st))

[out: ]
6
  • str() :: It converts any data type to string.
st = 12

print (type(st))
print (str(st), type(str(st)))

[out: ]
<class 'int'>
12 <class 'str'>
  • lower() :: Converts the string in the lower case.
s = "ParsIs"

print (s.lower())

[out: ]
parsis
  • upper() :: Converts the string into upper case.
s = "ParsIs"

print (s.upper())

[out: ]
PARSIS
  • strip() :: Removes space in the starting of the string.
a = "        Hello World   "

print (a)
print (a.strip())

[out: ]
        Hello World   
Hello World
  • isdigit() :: checks whether the values are digits or not.
a = "ParsIs"
b = "04"
c = "p04"

print (a.isdigit())
print (b.isdigit())
print (c.isdigit())

[out: ]
False
True
False
  • isalpha() :: Checkes whether all charactr in string is alphabetic or not.
# space will not be considered

a = "ParsIs"
b = "Par04"
c = "04"

print (a.isalpha())
print (b.isalpha())
print (c.isalpha())

[out: ]
True
False
False
  • isspace() :: Returns true if all characters in a string are spaces.
s = "Hello world "
st = "  "

print (s.isspace())
print (st.isspace())

[out: ]
False
True
  • startswith() :: It takes a string as an argument, and returns true if the string starts with a particular character given.
# Case-sensitive

s = "Hello world "
print (s.startswith('H'))
print (s.startswith('h'))

[out: ]
True
False
  • title() :: Returns first the words of the string into uppercase.
s = "hello world "

print (s.title())

[out: ]
Hello World 
  • Islower() :: Returns true if all characters are in lower case.
s = "hello world "
print (s.islower())

s = "Hello world "
print (s.islower())

[out: ]
True
False
  • endswith() :: It takes a string as an argument, and returns true if the string ends with a particular character given.
# Case-sensitive

s = "Hello world "

print (s.endswith(' '))
print (s.endswith('D'))

[out: ]
True
False
  • find() :: It takes an argument and returns the index of the substring
# -1 shows when that value is not there

s = "Hello world "

print (s.find('world'))
print (s.find('w'))
print (s.find('world!!'))

[out: ]
6
6
-1
  • replace() :: It takes two arguments. The first is the substring to be replaced. The second is the substring to replace with.
# Replace all the occurance of the string

s = "Hello world Hello"
print (s.replace('Hello','Hi'))

[out: ]
Hi world Hi
  • split() :: It takes one argument. The string is then split around every occurrence of the argument in the string.
# String will split around every occurance

s = "Hello world "
print (s.split(' '))

[out: ]
['Hello', 'world', '']
  • join() :: It takes a list as an argument and joins the elements in the list using the string it is applied on.
# Joins the characters list is applied on

a = "Hello"
b = '4_'
print (b.join(a))

[out: ]
H4_e4_l4_l4_o
  • capitalize() :: Returns the string with the first character capitalized and the rest of the characters in lower case.
# Returns first word of the string into uppercase

a = "hello, how are you?"
print(a.capitalize())

[out: ]
Hello, how are you?
  • swapcase() :: Provides the swap of the character.
a = "Hello, how are you?"
print(a.swapcase())

[out: ]
hELLO, HOW ARE YOU?
  • isupper()
a="Hello"
b="hello"
c="HELLO"

print(a.isupper())
print(b.isupper())
print(c.isupper())

[out: ]
False
False
True
  • isdecimal() :: 0 to 9 value is decimal else false.
a = "9"
b = "9.9"
c = "nine"

print(a.isdecimal())
print(b.isdecimal())
print(c.isdecimal())

[out: ]
True
False
False
  • isalnum() :: Checks alphabets and numbers without space.
a = "abc123"
b = "123"
c = "abc"
d = "jsak56@"
e = "jsak 56"

print(a.isalnum())
print(b.isalnum())
print(c.isalnum())
print(d.isalnum())
print(e.isalnum())

[out: ]
True
True
True
False
False

Type specific operations on strings

  • max() :: Finds the maximum.
a = "C","c"

print (max(1, 3, 2, 5, 4))
print (max(a))

[out: ]
5
c
  • min() :: Finds the minimum.
a = "C","c"

print (min(1, 3, 2, 5, 4))
print (min(a))

[out: ]
1
C
  • count() :: Returns the total count of the value.
a = "Python is awesome, isn't it?"

print(a.count("t"))
print(a.count("is"))

#it will find only from index 0 to 12

print(a.count("is",0,12))

[out: ]
3
2
1

String Operators

  • Comparison Operators.
a = "Python"
b = "Python"

print (a == b)

[out: ]
True
a, b = "C","c"

print (a > b)

[out: ]
False
  • Arithmetic Operators.
a, b = "C","c"

print (a + b)

[out: ]
Cc
a, b = "C",3

print (a * b)

[out: ]
CCC
  • Membership Operators.
a = "apple"

print ("p" in a)

[out: ]
True
a = "apple"

print ("p" not in a)

[out: ]
False
  • Identity Operators.
a = "apple"
b = "Apple"

print (a is b)

[out: ]
False
a = "apple"
b = "apple"

print (a is b)

[out: ]
True

FIND THE WHOLE CODE ON GITHUB:

https://github.com/parsispresswala/Prasik-s-Blogs/blob/master/Basic%20Python/05%20-%20Strings%20in%20Python.ipynb