Python Strings

Balasaheb Garule

6 months ago

Python Strings | insideAIML
Table of Content
What are Python Strings?
Declare Python String?
Use Quotes inside Python String
Spanning a String Across Multiple Lines
Python String Operations
   Access the Python String
       1.  How to display a single character?
       2. How to Slicing a String in Python?
       3. Reverse a String using Slicing
   Python String Concatenation
   Python String Formating
       1. f-strings
       2. format() method
       3. % operator
Escape Sequences in Python
String Conversion
  • Python string to int
  • Python string to list
  • Python str to float
Python String Functions
1. len()
2. str()
3. lower() and upper()
4. strip()
5. isdigit()
6. isalpha()
7. isspace()
8. startswith()
9. endswith()
10. find()
11. replace()
12. split()
13. join()
Summary

What are Python Strings?

          Python strings are sequences of characters. It is an ordered collection and immutable.’str’ class is used for python strings. Identify the class of variables using the type() method.
e.g.   
type(“Cats are cute”)
Output
<class ‘str’>
Python doesn’t support char data-type like C++ or Java.

Declare Python String

          We can use single quotes (‘’) or double quotes for declaring python strings.
e.g.
s='Cats are cute'      # python string example

print(s)
Output
Cats are cute
s=" Cats are cute "     # python string example

print(s)
Output
Cats are cute
However, you cannot use both quotation marks for declaring string.
e.g.
s= ‘Cats are cute”    # python string example
Output
SyntaxError: EOL while scanning string literal

Use Quotes inside Python String

          We cannot use the same quotation mark for use of quotes inside the python string.
 s="Cats are "cute""     # python string example
Output
SyntaxError: invalid syntax
For a double quote, we can use single quotes or for a single quote, we can use double-quotes.
s=’Cats are "cute"'	# python string example

print(s)
Output
Cats are “cute”
Or
s="Cats are 'cute'"	# python string example

print(s)
Output
Cats are ‘cute’
You can use multiple quotes.
e.g.
s="'Cats' 'are' 'cute'"	# python string example

print(s)
Output
‘Cats’ ‘are’ ‘cute’

Spanning a String Across Multiple Lines

          For spanning a string across multiple lines we can use triple quotes.
s="""Welcome		

to

insideaiml"""		# python string example

print(s)
Output
Welcome

to

insideaiml
We can use a backward slash to preserve the newline in the program but not in the program output.
e.g.
s="""Welcome\

to\

insideaiml"""		# python string example

print(s)
Output
Welcome to insideaiml

Python String Operations

          Following are the python string operations

Access the Python String

          A string is immutable; it can’t be modified.
s="Cats"

s[0]="H"
Output
Traceback (most recent call last):File “<pyshell#22>”, line 1, in <module>

s[0]=”H”

TypeError: ‘str’ object does not support item assignment
But you can access a string. .         .
s="Cats are cute"	# python string example

s
Output
‘Cats are cute’

print(s)
Output
Cats are cute 

How to display a single character?

          We can use indexing to display a single character. index starts from 0.
s="Cats are cute"

s[1]
Output
‘a’

How to Slicing a String in Python?

          Slicing a string in python using the following syntax.
 
str_object[start_pos:end_pos:step]
e.g.
s="Cats are cute"

s[3:8]
Output
‘s are’
Here, end_pos is excluded. Index start from 0.
e.g.           
s[:8]
Output
‘Cats are’
This prints characters from the start to character 7.
s[9:]
Output
‘ ut’
This prints characters from character 9 to the end of the string.
s[:]
Output
‘Cats are cute’
This prints the whole string.
s[:-2]
Output
‘Cats are cu’
It starts printing the character from the beginning to the second last character from the end.
s[-2:]
Output
‘te’
It prints characters from the second last character from the end to the end of the string.
s[-3:-2]
Output
‘u’
It prints characters from three characters from the end of a string to the second last character.
It returns empty strings.
s[-3:-3]
Output
 s[3:3]
Output
‘’

Reverse a String using Slicing

Reverse the string using slicing. 
e.g.
s = 'insideaiml'

reverse_str = s[::-1]

print(reverse_str)
Output
lmiaedisni
List of strings in python
# list of strings in python

names = ["amol", "rohan", "manisha"]

# print the list of strings

print(names)

[‘amol’, ‘rohan’, ‘manish’]

# loop over the names list, and  print each string one at a time

for name in names:

     print(name)
Output
amol

rohan

manisha

Python String Concatenation

          Python string concatenation is combining the strings. Python Strings can combine using the concatenation operator ”+”.
e.g.
 x='Welcome to, '

 y='insideaiml'

 x+y		# Python string concatenation
Output
‘Welcome to insideaiml’    
e.g.
 s='bye '
print(2*s)
Output
bye bye
we can not concatenate strings into numbers.
e.g.
'40'+10
Output
	Traceback (most recent call last):

  		File "<string>", line 1, in <module>

	TypeError: can only concatenate str (not "int") to str

Python String Formatting 

          We can format python strings simply using the commas in the print() method. 
e.g.
 city=Pune

 print("Age:",30,"City:",city)
Output
Age: 30 City: Pune
In python, formatting methods are available as follows:

f-strings

          f-string python formatting technique use for formatting the string using the letter ‘f’ precedes the string, and the variables are used using curly braces “{}” in their places.
e.g.
name = ”insiadeaiml”

print(f"Welcome to  {name}") # f string python
Output
Welcome to insideaiml

format() method

          format() method use to format python string.It use argument separated by commas.
Syntax:
String.format(value1, value2,)
We can use it three ways 
str1 = "My name is {fname} and roll no is {rollno}".format(fname = "Rohan",rollno= 1)

str2 = "My name is  {0} and roll no is {1} ".format( "Rohan", 1)

str3 = "My name is  {} and roll no is {}".format( "Rohan", 1)

print(str1)

print(str2)

print(str3)           
Output
My name is  Rohan and roll no is 1

My name is  Rohan and roll no is 1 

My name is  Rohan and roll no is 1I love cats

% operator

          % operator used for to access variable.%s is used for string
e.g.
Str1='Cats'

Str2 =’Dogs’

 print("I love %s and %s" %(Str1,Str2))
          
Output
I love Cats and Dogs
%d is used for integers and %f used for floating-point numbers

Escape Sequences in Python

          In Python following sequences are available.
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value
e.g.
str1 = 'It\'s Amazing.'

print(str1) 

str2 = "This will insert one \\ (backslash)."

print(str2) 

str3 = "Hello\nWorld!"

print(str3)

str4 = "Hello\rWorld!"	

print(str4) 

str4 = "Hello\tWorld!"

print(str4) 

#This example erases one character (backspace):

str5 = "Hello \bWorld!"

print(str5) 

#A backslash followed by three integers will result in a octal value:

Str6 = "\151\156\163\151\144\145\141\151\155\154"

print(str6) 

#A backslash followed by an 'x' and a hex number represents a hex value:

str7 ="\x69\x6e\x73\x69\x64\x65\x61\x69\x6d\x6c"

print(str7)
Output
It's Amazing.

This will insert one \ (backslash).

Hello

World!

Hello

World!

Hello	World!

Hello  World!

insideaiml

insideaiml

String Conversion

Python string to int

          We can use the int() method to convert a python string to int.
e.g.
s = “100”

print(type(s))

n = int(s)

print(type(n))

print(n)
output
<class 'str'>

<class 'int'>

100

Python String to list

          To convert python string to list need a split() method which use delimiter as argument
syntax:
string.split(delimiter)
e.g.
s = “welcome to insideaiml” 

list1 = s.split(“ “) #use delimiter as a space “ “
output
list1

['welcome', 'to', 'insideaiml'] #string to list in python
Example demonstrates the string to list in python conversion.

Python str to float

          Python str to float type conversion uses float() method.
e.g.
s = "3.14"

print(s)

print(type(s))

dec = float(s)   #string to float in python

print(dec)

print(type(dec))
output
3.14

<class 'str'>

3.14

<class 'float'>               #string to float in python

Python String Functions

          Python provides us with several functions that we can apply on strings or to create strings.

len()

         It returns the length of the string
s='insideaiml'

len(s)
Output
10
It also uses it to find the length of a slice of the string is.
e.g.
 len(s[2:])
Output
8

str()

          str in python used for type casting into string.str in python converts int to string, float to string, complex to string and so on.
e.g.
s= str(5+3j)

print(type(s))

print(s)
Output
<class 'str'>

(5+3j)

lower() and upper()

          Get uppercase and lowercase strings using lower() method and upper()method respectively.
s=”Python”

a.lower()
Output
python
s.upper()
Output
PYTHON

strip()

          Strip() method removes whitespaces from the beginning and end of the string.
s='  Python  '

s.strip()
Output
‘Python’

isdigit()

          If the string contains all digit returns True.
e.g.1
s=”555”

s.isdigit()
Output
True
e.g. 2
s='pi3.14'

a.disdigit()
Output
False

isalpha()

          If string character is alphabat then returns True.
s=’python’

s.isalpha()
Output
True
s='abc4'

s.isalpha()
Output
False

isspace()

          If string is space characters return True. 
e.g.
s='   '

s.isspace()
Output
True
s=' ab  '

s.isspace()
Output
False

startswith()

          It used to check if a string started with a specified character or word.
e.g
s=”insideaiml”          

s.startswith('in')
Output
True

endswith()

          It used to check string end  with specified character or word.
s=”python”

s.endswith('on')
Output
True

find()

          It used to find provided substring into string.
e.g. 
# check if the string contains substring python

s=”insideaiml”

s.find(side)
Output
2
Return -1 if substring is not found.
s.find(on)
Output
-1

replace()

          It replaces substring in the provided string. It takes two arguments part of a string which is replaced by substring.
“Mohan”.replace(‘Mo’, 'Ro')
Output
‘Rohan’

split()

          It split the string using provided argument.
e.g.
'I, am, Student'.split(',')
Output
[‘I’, ‘ am’, ‘ student’]

join()

          It is used to join the strings using separator.
e.g.
"+".join(['jan','feb','march'])
Output
'jan+feb+march'

Summary

          In this blog, we learned about python strings with string functions and Operators, and how to declare and access them.
We also learned about python string concatenation and formatters in python.
Finally, we learned about Python string functions that we can perform on strings.
    
Liked what you read? Then don’t break the spree. Visit our blog page to read more awesome articles. 
Or if you are into videos, then we have an amazing Youtube channel as well. Visit our InsideAIML Youtube Channel to learn all about Artificial Intelligence, Deep Learning, Data Science and Machine Learning. 
Keep Learning. Keep Growing. 

Submit Review