0% found this document useful (0 votes)
2 views10 pages

Python String handling codes

This document is a comprehensive tutorial on string handling in Python, covering topics such as string creation, access, modification, operations, and formatting. It includes examples of string methods, slicing, concatenation, and membership tests, along with explanations of built-in functions and string immutability. Additionally, it discusses string formatting techniques and provides examples of loops and conditional statements in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
2 views10 pages

Python String handling codes

This document is a comprehensive tutorial on string handling in Python, covering topics such as string creation, access, modification, operations, and formatting. It includes examples of string methods, slicing, concatenation, and membership tests, along with explanations of built-in functions and string immutability. Additionally, it discusses string formatting techniques and provides examples of loops and conditional statements in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 10

Python String handling astring = "Hello world!

"

Table of Contents print(astring[3:7])


 What is String in Python?
 How to create a string in Python?
print(astring[3:7:1])
 How to access characters in a string?
 How to change or delete a string? There is no function like strrev in C to reverse
 Python String Operations a string. But with the above mentioned type of
o Concatenation of Two or More slice syntax you can easily reverse a string
Strings like this
o Iterating Through String
o String Membership Test astring = "Hello world!"
o Built-in functions to Work with
Python print(astring.upper())
 Python String Formatting
o Escape Sequence print(astring.lower())
o Raw String to ignore escape
sequence astring = "Hello world!"
o The format() Method for Formatting
Strings print(astring.startswith("Hello"))
o Old style formatting
 Common Python String Methods print(astring.endswith("asdfasdfasdf"))

astring = "Hello world!"


Basic String Operations
afewwords = astring.split(" ")
Strings are bits of text. They can be defined as
anything between quotes: # First occurrence of "a" should be at index 8

astring = "Hello world!" print("The first occurrence of the letter a =


%d" % s.index("a"))
astring2 = 'Hello world!'
# Number of a's should be 2
astring = "Hello world!"
print("a occurs %d times" % s.count("a"))
print("single quotes are ' '")
# Slicing the string into bits
print(len(astring))
print("The first five characters are '%s'" %
astring = "Hello world!" s[:5]) # Start to 5

print(astring.index("o")) print("The next five characters are '%s'" %


s[5:10]) # 5 to 10
astring = "Hello world!"
print("The thirteenth character is '%s'" %
print(astring.count("l")) s[12]) # Just number 12

astring = "Hello world!" print("The characters with odd index are '%s'"
%s[1::2]) #(0-based indexing)
print(astring[3:7])
print("The last five characters are '%s'" % s[-
astring = "Hello world!" 5:]) # 5th-from-last to end
print(astring[3:7:2]) # Convert everything to uppercase

Python Tutorial By Prof Sanjay Wankhade.


1
print("String in uppercase: %s" % of items in a string by using the
s.upper()) slicing operator (colon).
# Convert everything to lowercase
str = 'programiz'
print("String in lowercase: %s" % print('str = ', str)
s.lower())
#first character
# Check how a string starts
print('str[0] = ', str[0])
if s.startswith("Str"):
#last character
print("String starts with 'Str'. Good!") print('str[-1] = ', str[-1])
# Check how a string ends #slicing 2nd to 5th character
if s.endswith("ome!"): print('str[1:5] = ', str[1:5])
print("String ends with 'ome!'. Good!") #slicing 6th to 2nd last character

# Split the string into three separate print('str[5:-2] = ', str[5:-2])


strings, If we try to access index out
of the range or use decimal
# each containing only a word
number, we will get errors.
print("Split the words of the string: %s" % How to change or delete a
s.split(" ")) string?
How to access characters in a Strings are immutable. This
string? means that elements of a string
We can access individual cannot be changed once it has
characters using indexing and been assigned. We can simply
a range of characters using reassign different strings to the
slicing. Index starts from 0. same name.
Trying to access a character
out of index range will raise >>> my_string = 'programiz'>>>
an IndexError. The index must my_string[5] =
be an integer. We can't use 'a'...TypeError: 'str' object
float or other types, this will does not support item
result into TypeError. assignment>>> my_string =
'Python'>>> my_string'Python'

Python allows negative indexing


for its sequences. Python String Operations
Concatenation of Two or More
The index of -1 refers to the last
Strings
item, -2 to the second last item
and so on. We can access a range

Python Tutorial By Prof Sanjay Wankhade.


2
Joining of two or more strings for letter in 'Hello World':
into a single one is called
concatenation. if(letter == 'l'):
The + operator does this in count += 1
Python.
print(count,'letters found')

String Membership Test


The * operator can be used to
We can test if a sub string exists
within a string or not, using the
repeat the string for a given
keyword in.
number of times
>> 'a' in 'program'
str1 = 'Hello'
True
str2 ='World!'
>>> 'at' not in 'battle'
False
# using +

print('str1 + str2 = ', str1 + str2)


Built-in functions to
Work with Python
Various built-in functions that
# using * work with sequence, works with
print('str1 * 3 =', str1 * 3) string as well.

Some of the commonly used ones


If we want to concatenate strings are enumerate() and len().
in different lines, we can use The enumerate() function returns an
parentheses. enumerate object. It contains the
index and value of all the items in
>>> # two string literals the string as pairs. This can be
together>>> 'Hello useful for iteration.
''World!''Hello World!'
>>> # using parentheses>>> s = str = 'cold'
('Hello '... 'World')>>>
s'Hello World' # enumerate()
list_enumerate=
Iterating Through String
list(enumerate(str))
Using for loop we can iterate
through a string. Here is an print('list(enumerate(str) = ',
example to count the number of list_enumerate)
'l' in a string.

count = 0 #character count

Python Tutorial By Prof Sanjay Wankhade.


3
print('len(str) = ', len(str))
# escaping single quotes

print('He said, "What\'s there?"')


Python String Formatting

Escape Sequence
# escaping double quotes
If we want to print a text like -He
said, "What's there?"- we can print("He said, \"What's there?\"")
neither use single quote or
>>> print("C:\\Python32\\Lib")
double quotes. This will result
into SyntaxError as the text itself C:\Python32\Lib
contains both single and double >>> print("This is printed\nin
quotes. two lines")This is printedin
two lines
>>> print("He said, "What's
there?"") >>> print("This is \x48\x45\
x58 representation")This is
... HEX representation
SyntaxError: invalid syntax
Raw String to ignore
>>> print('He said, "What's
there?"')
escape sequence
Sometimes we may wish to
...
ignore the escape sequences
SyntaxError: invalid syntax inside a string. To do this we can
place r or R in front of the string.
This will imply that it is a raw
string and any escape sequence
An escape sequence starts with a inside it will be ignored.

backslash and is interpreted >>> print("This is \x61 \ngood


example")
differently. If we use single quote This is a good example
>>> print(r"This is \x61 \ngood
to represent a string, all the
example")

single quotes inside the string This is \x61 \ngood example

must be escaped. Similar is the The format() Method for


Formatting Strings
case with double quotes. The format() method that is
# using triple quotes available with the string object is
very versatile and powerful in
print('''He said, "What's there?"''') formatting strings. Format strings

Python Tutorial By Prof Sanjay Wankhade.


4
contains curly braces {} as >>>
placeholders or replacement "PrOgRaMiZ".lower()'programiz'
fields which gets replaced. >>>
"PrOgRaMiZ".upper()'PROGRAMIZ'
>>> "This will split all words
We can use positional arguments
into a list".split()
or keyword arguments to specify
the order. ['This', 'will', 'split',
'all', 'words', 'into', 'a',
'list']

# default(implicit) order >>> ' '.join(['This', 'will',


'join', 'all', 'words',
default_order = "{}, {} and 'into', 'a', 'string'])
{}".format('John','Bill','Sean')
'This will join all words into
print('\n--- Default Order ---') a string'

print(default_order) >>> 'Happy New Year'.find('ew')

# order using positional argument 7

positional_order = "{1}, {0} and >>> 'Happy New


{2}".format('John','Bill','Sean') Year'.replace('Happy','Brillia
nt')'Brilliant New Year'
print('\n--- Positional Order ---')
print(positional_order)
conditions
# order using keyword argument
x=2
keyword_order = "{s}, {b} and
{j}".format(j='John',b='Bill',s='Sean') print(x == 2) # prints out True

print('\n--- Keyword Order ---') print(x == 3) # prints out False


print(keyword_order) print(x < 3) # prints out True

Common Python
String Methods Boolean operators

There are numerous methods name = "John"


available with the string object. age = 23
The format() method that we
mentioned above is one of them. if name == "John" and age == 23:
Some of the commonly used
print("Your name is John, and you are
methods also 23 years old.")
are lower(), upper(), join(), split(),
find(), replace() etc. Here is a if name == "John" or name == "Rick":
complete list of all the built-in
print("Your name is either John or
methods to work with strings in
Rick.")
Python.

Python Tutorial By Prof Sanjay Wankhade.


5
</do></do></another></do></
The "in" operator statement>

The "in" operator could be used to check


if a specified object exists within an
x=2
iterable object container, such as a list:
if x == 2:
name = "John"
print("x equals two!")
if name in ["John", "Rick"]:
else:
print("Your name is either John or
Rick.") print("x does not equal to two.")

Python uses indentation to define code


blocks, instead of brackets. The standard
Python indentation is 4 spaces, although The 'is' operator
tabs and any other space size will work, as
Unlike the double equals operator "==",
long as it is consistent. Notice that code
the "is" operator does not match the values
blocks do not need any termination.
of the variables, but the instances
Here is an example for using Python's "if" themselves. For example:
statement using code blocks:
 x = [1,2,3]
if <statement is="" true="">:  y = [1,2,3]
 print(x == y) # Prints out True
<do something="">
 print(x is y) # Prints out False
....
.... The "not" operator

elif <another statement="" is="" Using "not" before a boolean expression


true="">: # else if inverts it:
<do something="" else=""> print(not False) # Prints out True

.... print((not False) == (False)) # Prints


out False
....
else: Exercise
<do another="" thing=""> Change the variables in the first section,
so that each if statement resolves as True.
....
# change this code
....

Python Tutorial By Prof Sanjay Wankhade.


6
number = 10
second_number = 10 A palindrome is a string

first_array = [] which is same read forward or


second_array = [1,2,3]
backwards.
# Program to check if a string
if number > 15:
# is palindrome or not
print("1")

# change this value for a different output


if first_array: my_str = 'aIbohPhoBiA'
print("2")

# make it suitable for caseless comparison


if len(second_array) == 2: my_str = my_str.casefold()
print("3")
# reverse the string

rev_str = reversed(my_str)
if len(first_array) + len(second_array)
== 5:
# check if the string is equal to its reverse
print("4")
if list(my_str) == list(rev_str):

print("It is palindrome")
if first_array and first_array[0] == 1: else:
print("5") print("It is not palindrome")

if not second_number:
print("6")

Loops
There are two types of loops in Python,
for and while.
The "for" loop
For loops iterate over a given sequence.
Here is an example:

Python Tutorial By Prof Sanjay Wankhade.


7
primes = [2, 3, 5, 7]
for prime in primes: # To take input from the user
print(prime) # my_str = input("Enter a string: ")
# remove punctuation from the string

For loops can iterate over a sequence of no_punct = ""


numbers using the "range" and "xrange" for char in my_str:
functions. The difference between range if char not in punctuations:
and xrange is that the range function
returns a new list with numbers of that no_punct = no_punct + char
specified range, whereas xrange returns an # display the unpunctuated string
iterator, which is more efficient. (Python 3
print(no_punct)
uses the range function, which acts like
xrange). Note that the range function is
zero based. Python Program to Count the Number of
Each Vowel

# Prints out the numbers 0,1,2,3,4
# Program to count the number of each
for x in range(5): vowel in a string
print(x) # string of vowels
vowels = 'aeiou'
# Prints out 3,4,5 # change this value for a different result
for x in range(3, 6): ip_str = 'Hello, have you tried our
turorial section yet?'
print(x)
# uncomment to take input from the user
#ip_str = input("Enter a string: ")
# Prints out 3,5,7
# make it suitable for caseless
for x in range(3, 8, 2): comparisions
print(x) ip_str = ip_str.casefold()
# make a dictionary with each vowel a
key and value 0
Python Program to Remove
Punctuations From a String count = {}.fromkeys(vowels,0)
# count the vowels
# define punctuation
for char in ip_str:
punctuations = '''!()-[]{};:'"\,<>./?@#$
%^&*_~''' if char in count:
my_str = "Hello!!!, he said ---and went." count[char] += 1

Python Tutorial By Prof Sanjay Wankhade.


8
print(count) Python Program to Check Armstrong
Number

Python Program to Sort Words in # Python program to check if


Alphabetic Order the number provided by the user
is an Armstrong number or not
# Program to sort alphabetically the # take input from the user# num
words form a string provided by the = int(input("Enter a number:
user "))

# change this value for a different result # initialize sum

my_str = "Hello this Is an Example sum = 0


With cased letters" # find the sum of the cube of
each digit
# uncomment to take input from the
user temp = numwhile temp > 0:

#my_str = input("Enter a string: ") digit = temp % 10

# breakdown the string into a list of sum += digit ** 3


words temp //= 10
words = my_str.split() # display the resultif num ==
sum:
# sort the list
print(num,"is an Armstrong
words.sort() number")else:
# display the sorted words print(num,"is not an
print("The sorted words are:") Armstrong number")

for word in words:


print(word) "break" and "continue" statements
break is used to exit a for loop or a while
while" loops loop, whereas continue is used to skip the
current block, and return to the "for" or
While loops repeat as long as a certain "while" statement. A few examples:
boolean condition is met. For example:
# Prints out 0,1,2,3,4
# Prints out 0,1,2,3,4
count = 0
while True:
count = 0
print(count)
while count < 5:
count += 1
print(count)
if count >= 5:
count += 1 # This is the same as
count = count + 1 break

Python Tutorial By Prof Sanjay Wankhade.


9
break
# Prints out only odd numbers - print(i)
1,3,5,7,9
else:
for x in range(10):
print("this is not printed because
# Check if x is even for loop is terminated because of break
but not due to fail in condition")
if x % 2 == 0:
continue
print(x)

can we use "else" clause for loops?


unlike languages like C,CPP.. we can
use else for loops. When the loop
condition of "for" or "while" statement
fails then code part in "else" is executed.
If break statement is executed inside for
loop then the "else" part is skipped. Note
that "else" part is executed even if there is
a continue statement.
Here are a few examples:
# Prints out 0,1,2,3,4 and then it
prints "count value reached 5"

count=0
while(count<5):
print(count)
count +=1
else:
print("count value reached %d" %
(count))

# Prints out 1,2,3,4


for i in range(1, 10):
if(i%5==0):

Python Tutorial By Prof Sanjay Wankhade.


10

You might also like