PYTHON STRINGS

 

In Python, a string is an immutable sequence of Unicode characters used to store and manipulate text

Strings in python are surrounded by either single quotation marks, or double quotation marks.

'hello' is the same as "hello".

we can display the string using print() function

 SYNTAX:

name = "ramakrishna"

nickname = 'nani'

print(name)

print(nickname)


OUTPUT:

ramakrishna

nani

 QUOTES INSIDE QUOTES

We can quotes inside a string  and they do not match the quotes surrounding the string

 SYNTAX:

name = "my name is 'ramakrishna'"

nickname = 'my nick name is "nani"'

print(name)

print(nickname)


OUTPUT:

my name is 'ramakrishna'

my nickname is "nani"

MULTILINE STRING

Using three single or double quotes

 SYNTAX:

names = """ 'students list'

ramakrishna

nani

priya """

subjects = ''' Subject

English

Telugu

Hindi '''

print(names)

print(subjects)


OUTPUT:

'Student lise'

ramakrishna

nani

priya

subjects

English

Telugu

Hindi

SLICING

We can return a range of the string by using slicing and specifying the starting index and ending index and seperated by colon and index start with 0

  • Slice from the range: Slicing specify both starting and ending endex and seperated by colon 
  • Slice from the start : by leaving out of the start index,
  • Slice to the end: By leaving out of the end indem 
  • Megative slicing: 


 SYNTAX:

range= "Hello World"

start= 'Hello World'

end = "Hello world"

negative = "Hello World"


print(range[2:5])

print(start[:5])

print(end[2:])


OUTPUT:

ll0

Hello

llo World


MODIFY STRING

By using built in methods we can modify string

  1. UPPER CASE
  2. LOWER CASE
  3. REMOVE WHITESPACES (STRIP)
  4. REPLACE
  5. SPLIT
  • UPPER CASE
upper() is used to modify the string returs in upper case

 SYNTAX:

name = "ramakrishna"

print(name.upper())


OUTPUT:

RAMAKRISHNA

  • LOWER CASE

The lower() method returns the string in lower case 

 SYNTAX:

name = "RAMAKRISHNA"

print(name.lower())


OUTPUT:

ramakrishna

  • 3REMOVE WHITESPACES (STRIP)

The strip() method removes any whitespace from the beginning or the end

 SYNTAX:

name = " RAMAKRISHNA "

print(name.strip())


OUTPUT:

ramakrishna

  • REPLACE

The replace method replaces a string with another string:

 SYNTAX:

name = "Hello world!"

print(name.replace("world!", "python"))


OUTPUT:

Hello python

  • SPLIT

The method returns a list where the text between the specified separator becomes the list items.

 SYNTAX:

name = "Hello, world!"

print(name.split(" , "))


OUTPUT:

['Hello' , 'world!"]

CONCATENATE 

To concatenate, or combine, two strings you can use the + operator.

 SYNTAX:

a = "Hello"

b = "world!"

c = a + b 

d = a + " " + b

print(c) / print (a + b)

print(d) / print(a + "  " +b)


OUTPUT:

Helloworld!

Hello world!