Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python String Handling_SanjayWankhade-1

The document provides a comprehensive overview of string handling in Python, including string creation, access, modification, and various operations such as concatenation and formatting. It covers built-in string methods, escape sequences, and examples of common string manipulations. Additionally, it discusses loops and conditional statements relevant to string processing.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python String Handling_SanjayWankhade-1

The document provides a comprehensive overview of string handling in Python, including string creation, access, modification, and various operations such as concatenation and formatting. It covers built-in string methods, escape sequences, and examples of common string manipulations. Additionally, it discusses loops and conditional statements relevant to string processing.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Python String handling astring = "Hello world!

"

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

 What is String in Python?


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

Python Tutorial By Prof Sanjay Wankhade.


1
5:]) # 5th-from-last to end The index of -1 refers to the last
item, -2 to the second last item
# Convert everything to uppercase and so on. We can access a range
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


print('str[1:5] = ', str[1:5])
if s.endswith("ome!"):
#slicing 6th to 2nd last character
print("String ends with 'ome!'. Good!")
print('str[5:-2] = ', str[5:-2])
# Split the string into three separate
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
assignment>>> my_string =
result into TypeError.
'Python'>>> my_string'Python'

Python allows negative indexing Python String Operations


for its sequences.

Python Tutorial By Prof Sanjay Wankhade.


2
Concatenation of Two or More print(count,'letters found')
Strings
String Membership Test
Joining of two or more strings
into a single one is called We can test if a sub string exists
concatenation. within a string or not, using the
keyword in.
The + operator does this in
Python.
>> 'a' in 'program'
True
The * operator can be used to >>> 'at' not in 'battle'
False
repeat the string for a given
Built-in functions to
number of times
Work with Python
str1 = 'Hello'
str2 ='World!' Various built-in functions that
work with sequence, works with
# using +
print('str1 + str2 = ', str1 + str2) string as well.

# using * Some of the commonly used ones


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

Using for loop we can iterate #character count


through a string. Here is an print('len(str) = ', len(str))
example to count the number of
'l' in a string.
Python String Formatting
count = 0 Escape Sequence
for letter in 'Hello World':
if(letter == 'l'): If we want to print a text like -He
count += 1 said, "What's there?"- we can

Python Tutorial By Prof Sanjay Wankhade.


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

An escape sequence starts with a >>> print("This is \x61 \ngood


example")
backslash and is interpreted This is a good example
>>> print(r"This is \x61 \ngood
differently. If we use single quote
example")

to represent a string, all the This is \x61 \ngood example

single quotes inside the string The format() Method for


Formatting Strings
must be escaped. Similar is the
The format() method that is
case with double quotes. available with the string object is
very versatile and powerful in
# using triple quotes formatting strings. Format strings
print('''He said, "What's there?"''') contains curly braces {} as
# escaping single quotes placeholders or replacement
print('He said, "What\'s there?"') fields which gets replaced.

# escaping double quotes We can use positional arguments


print("He said, \"What's there?\"") or keyword arguments to specify
>>> print("C:\\Python32\\Lib") the order.
C:\Python32\Lib

# default(implicit) order

Python Tutorial By Prof Sanjay Wankhade.


4
default_order = "{}, {} and >>> ' '.join(['This', 'will',
{}".format('John','Bill','Sean') 'join', 'all', 'words',
'into', 'a', 'string'])
print('\n--- Default Order ---')
'This will join all words into
print(default_order) a string'
# order using positional argument >>> 'Happy New Year'.find('ew')
positional_order = "{1}, {0} and 7
{2}".format('John','Bill','Sean')
>>> 'Happy New
print('\n--- Positional Order ---') Year'.replace('Happy','Brillia
nt')'Brilliant New Year'
print(positional_order)
# order using keyword argument
conditions
keyword_order = "{s}, {b} and
{j}".format(j='John',b='Bill',s='Sean') x=2
print('\n--- Keyword Order ---') print(x == 2) # prints out True
print(keyword_order) print(x == 3) # prints out False
Common Python print(x < 3) # prints out True
String Methods
Boolean operators
There are numerous methods
available with the string object. name = "John"
The format() method that we
mentioned above is one of them. age = 23
Some of the commonly used if name == "John" and age == 23:
methods
are lower(), upper(), join(), split(), print("Your name is John, and you are
find(), replace() etc. Here is a also 23 years old.")
complete list of all the built-in
methods to work with strings in if name == "John" or name == "Rick":
Python.
print("Your name is either John or
Rick.")
>>>
"PrOgRaMiZ".lower()'programiz'
>>> The "in" operator
"PrOgRaMiZ".upper()'PROGRAMIZ'
>>> "This will split all words The "in" operator could be used to check
into a list".split() if a specified object exists within an
['This', 'will', 'split', iterable object container, such as a list:
'all', 'words', 'into', 'a',
'list'] name = "John"
if name in ["John", "Rick"]:

Python Tutorial By Prof Sanjay Wankhade.


5
print("Your name is either John or print("x does not equal to two.")
Rick.")

Python uses indentation to define code


The 'is' operator
blocks, instead of brackets. The standard
Python indentation is 4 spaces, although Unlike the double equals operator "==",
tabs and any other space size will work, as the "is" operator does not match the values
long as it is consistent. Notice that code of the variables, but the instances
blocks do not need any termination. themselves. For example:
Here is an example for using Python's "if"  x = [1,2,3]
statement using code blocks:  y = [1,2,3]
if <statement is="" true="">:  print(x == y) # Prints out True
 print(x is y) # Prints out False
<do something="">
.... The "not" operator
.... Using "not" before a boolean expression
inverts it:
elif <another statement="" is=""
true="">: # else if print(not False) # Prints out True
print((not False) == (False)) # Prints
<do something="" else=""> out False
....
Exercise
....
Change the variables in the first section,
else:
so that each if statement resolves as True.
<do another="" thing="">
# change this code
.... number = 10
second_number = 10
.... first_array = []
second_array = [1,2,3]
</do></do></another></do></
statement> if number > 15:
print("1")

x=2 if first_array:
if x == 2: print("2")
print("x equals two!")
else: if len(second_array) == 2:
print("3")

Python Tutorial By Prof Sanjay Wankhade.


6
The "for" loop

if len(first_array) + len(second_array) For loops iterate over a given sequence.


== 5: Here is an example:
print("4")
primes = [2, 3, 5, 7]
for prime in primes:
if first_array and first_array[0] == 1:
print(prime)
print("5")

if not second_number: For loops can iterate over a sequence of


print("6")
numbers using the "range" and "xrange"
functions. The difference between range
and xrange is that the range function
returns a new list with numbers of that
specified range, whereas xrange returns an
A palindrome is a string iterator, which is more efficient. (Python 3
uses the range function, which acts like
which is same read forward xrange). Note that the range function is
zero based.
or backwards.

# Program to check if a string # Prints out the numbers 0,1,2,3,4
# is palindrome or not for x in range(5):
print(x)
# change this value for a different output
my_str = 'aIbohPhoBiA'
# Prints out 3,4,5
# make it suitable for caseless comparison for x in range(3, 6):
my_str = my_str.casefold() print(x)

# reverse the string # Prints out 3,5,7


rev_str = reversed(my_str) for x in range(3, 8, 2):
print(x)
# check if the string is equal to its reverse
if list(my_str) == list(rev_str):
print("It is palindrome")
else:
Python Program to Remove
print("It is not palindrome") Punctuations From a String

# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$
%^&*_~'''

Loops my_str = "Hello!!!, he said ---and went."

There are two types of loops in Python,


for and while. # To take input from the user

Python Tutorial By Prof Sanjay Wankhade.


7
# my_str = input("Enter a string: ")
# remove punctuation from the string Python Program to Sort Words in
no_punct = "" Alphabetic Order

for char in my_str: # Program to sort alphabetically the


if char not in punctuations: words form a string provided by the
user
no_punct = no_punct + char
# change this value for a different result
# display the unpunctuated string
my_str = "Hello this Is an Example
print(no_punct) With cased letters"
# uncomment to take input from the
user
Python Program to Count the Number of
Each Vowel #my_str = input("Enter a string: ")
# breakdown the string into a list of
# Program to count the number of each
words
vowel in a string
words = my_str.split()
# string of vowels
# sort the list
vowels = 'aeiou'
words.sort()
# change this value for a different result
# display the sorted words
ip_str = 'Hello, have you tried our
turorial section yet?' print("The sorted words are:")
# uncomment to take input from the user for word in words:
#ip_str = input("Enter a string: ") print(word)
# make it suitable for caseless
comparisions while" loops
ip_str = ip_str.casefold() While loops repeat as long as a certain
# make a dictionary with each vowel a boolean condition is met. For example:
key and value 0
# Prints out 0,1,2,3,4
count = {}.fromkeys(vowels,0)
count = 0
# count the vowels while count < 5:
for char in ip_str: print(count)
count += 1 # This is the same as
if char in count: count = count + 1
count[char] += 1 Python Program to Check Armstrong
print(count) Number

Python Tutorial By Prof Sanjay Wankhade.


8
# Python program to check if if x % 2 == 0:
the number provided by the continue
user is an Armstrong number or print(x)
not
# take input from the user# can we use "else" clause for loops?
num = int(input("Enter a
number: ")) unlike languages like C,CPP.. we can
# initialize sum use else for loops. When the loop
condition of "for" or "while" statement
sum = 0
fails then code part in "else" is executed.
# find the sum of the cube of If break statement is executed inside for
each digit
loop then the "else" part is skipped. Note
temp = numwhile temp > 0: that "else" part is executed even if there is
digit = temp % 10 a continue statement.
sum += digit ** 3 Here are a few examples:
temp //= 10 # Prints out 0,1,2,3,4 and then it prints
# display the resultif num == "count value reached 5"
sum:
count=0
print(num,"is an Armstrong while(count<5):
number")else: print(count)
print(num,"is not an count +=1
Armstrong number") else:
print("count value reached %d" %
(count))
"break" and "continue" statements
# Prints out 1,2,3,4
break is used to exit a for loop or a while for i in range(1, 10):
loop, whereas continue is used to skip the if(i%5==0):
current block, and return to the "for" or break
"while" statement. A few examples: print(i)
else:
# Prints out 0,1,2,3,4 print("this is not printed because
count = 0 for loop is terminated because of break
while True: but not due to fail in condition")
print(count)
count += 1
if count >= 5:
break

# Prints out only odd numbers -


1,3,5,7,9
for x in range(10):
# Check if x is even

Python Tutorial By Prof Sanjay Wankhade.


9

You might also like