String

A string in Python consists of a series or sequence of characters - letters, numbers, and special characters. Strings can be indexed - often synonymously called subscripted as well. Similar to C, the first character of a string has the index 0.

  1. Python use utf-8 encoding to define charcters

  2. String can be defined in single quotes as 'any string' or in double quotes as "any string"

  3. In python String can also be defined as

  4. """ line1

  5. line2

  6. multiline stirng """

  7. or

  8. ''' para1

  9. para2

  10. para3

  11. multiline'''

  12. String data type is a object of built-in String Class

Data Structure in Python

Finding ASCII values in python

ord("a")

chr(100)

97

'd'

  • Python is different in handling strings

  • Generally in other languages like c++, java, it reads string as array and characters

  • In Python, name = "a" is treated as string of length=1

  • Python deals only with strings, it doesn't know anything about characters

  • String is immutable data structure in python

How is it Immutable?

a = "Sahil", a[0] = "p" is not allowed in python

String Operation:

Case-1:

a = 10
b = 20
c = 30

print(str(a) + "-" + str(b) + "-" + str(c))

10-20-30

Case-2:

a = 10
b = 20
c = 30

#print(str(a) + "-" + str(b) + "-" + str(c))
print("%d-%d-%d" % (a,b,c))

10-20-30

Case-3:

a = "sahil"
b = 20
c = 30

#print(str(a) + "-" + str(b) + "-" + str(c))
print("%d-%d-%d" % (a,b,c))

This will give error

Case-4:

a = "sahil"
b = 20
c = 30

#print(str(a) + "-" + str(b) + "-" + str(c))
print("{}-{}-{}".format(a,b,c))

sahil-20-30

Case -5:

a = "sahil"
b = 20
c = 30

#print(str(a) + "-" + str(b) + "-" + str(c))
print("{1}-{2}-{0}".format(a,b,c))

20-30-sahil

Example - 1:

s1 = 'hello world'
s2 = "Hello World"
s3 ="""
Hi this is Strings in python.
        Python is an awesome language.
Strings are wide data type.
We can convert almost all data types into strings.
        Default input function of python returns a string.
"""
print(s1)
print(s2)
print(s3)

hello world

Hello World

Hi this is Strings in python.

Python is an awesome language.

Strings are wide data type.

We can convert almost all data types into strings.

Default input function of python returns a string.

Example - 2:

s = "He said,\"She is beautiful.\"" #backslash is known as escape charcter
k = 'He said,"She is beautiful."'  #If single quotes are used inside then double quotes outside and vice-versa
print(s)
print(k)

He said,"She is beautiful."

He said,"She is beautiful."

Properties of string

  1. Indexing # starts from 0 to n - 1 where n is the length of string use []

  2. Slicing # used to make sub-strings from strings used with start,end and step variable

Example - 3:

s = "Python"
#indexing in strings
print(s[3])
print(s[-3])

h

h

Example - 4:

#-12-11-10-9-8-7-6-5-4-3-2-1  (reverse indxing)
s = "Hello World!"
#   01234567891011
#s[start:end:step] always starts with start end end string in end-1 character
x = s[3:11]
y =  s[:]
z = s[:6]
p = s[6:]
print(x)
print(y)
print(z)
print(p)
print(s)

lo World

Hello World!

Hello

World!

Hello World!

Example - 5:

s = "Hello World!"
print(s[::-1])
print(s[:-1])
print(s[7:10:-1])
print(s[-12:-6])
print(s[-1:-13:-1])
print(s[::2])
print(s[::-2])

!dlroW olleH

Hello World

Hello

!dlroW olleH

HloWrd

!lo le

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.

Example - 6:

print("Methods1 and Attributes \rGyansetu")
print("hello \t world")
print("hello \nworld")

Gyansetu and Attributes

hello world

hello

world

Some Basic Functions of String

  1. swapcase

  2. upper

  3. lower

  4. strip, lstrip, rstrip

  5. find

  6. replace

  7. format

  8. center

Example - 7:

#none of these functions will change the string.
s = input("Enter a String : ")
print(s)
#swapcase used to change uppercase letters into lowercase letters and vice versa.
print("Swapcase : ",s.swapcase())

#change all letters into uppercase and return the string
print("Upper : ",s.upper())

#change all letters into lowercase and return the string
print("Lower : ",s.lower())

#strip is used to remove all leading and trailing spaces from string
print("Strip : ",s.strip())

#lstrip is used to remove left space and rstrip to remove rightspace
print("LStrip : ",s.lstrip())

print("RStrip : ",s.rstrip())

p = input("Enter pattern to search : ").strip().lower()  #Remove all the spaces and convert.string,into lowercase
 
print("Find Result : ",s.find(p)) #find a particular pattern in a particular string

#string formatting
print("String : {} \nPattern : {} ".format(s,p)) #{} is replaced with the parameters passedin format()function

print(s.center(1000,'*'))

Enter a String : ALL Dogs ARE Not cats

ALL Dogs ARE Not cats

Swapcase : all dOGS are nOT CATS

Upper : ALL DOGS ARE NOT CATS

Lower : all dogs are not cats

Strip : ALL Dogs ARE Not cats

LStrip : ALL Dogs ARE Not cats

RStrip : ALL Dogs ARE Not cats

Enter pattern to search : cats

Find Result : 21

String : ALL Dogs ARE Not cats Pattern : cats

* ALL Dogs ARE Not cats**

replace() is an inbuilt function in Python programming language that returns a copy of the string where all occurrences of a substring is replaced with another substring.

  1. string.replace(old, new, count) #syntax

  2. old – old substring you want to replace.

  3. new – new substring which would replace the old substring.

  4. count – the number of times you want to replace the old substring with the new substring. (Optional)

Example - 8:

string = "HI hello HI hello hi hello hi hello" 
   
# Prints the string by replacing hi by HI  
print(string.replace("hi", "HI"))  
  
# Prints the string by replacing only first 3 occurence of hello   
print(string.replace("hello", "HELLO", 3)) 

HI hello HI hello HI hello HI hello

HI HELLO HI HELLO hi HELLO hi hello

Last updated