[go: up one dir, main page]

0% found this document useful (0 votes)
26 views6 pages

String manipulation (1)

Uploaded by

asadsdsdwdf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views6 pages

String manipulation (1)

Uploaded by

asadsdsdwdf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Chapter - 9

String manipulation

Introduction-
• As we know, a sequence of characters enclosed in single quotes, double quotes or triple quotes (‘ ‘, “ “, ‘’’ ‘’’) is called a
string.
• In python, strings are immutable meaning they can’t be changed.
• In a String, each character remains at a unique position number or index number which goes from 0 to n-1 (n is the total
number of characters in the string).

String Creation-
1. By assigning value directly to the variable a = “Hello World”

2. By taking Input str1 = input(“Enter a string”)

Traversal of a string- Process to access each and every character of a string for the purpose of display or for some other
purpose is called string traversal.

str1 = 'Hello World!'


for ch in str1:
print(ch, end = ' ')

Output
HelloWorld!

Program to read a string and prints it in reverse order


str1 = input(“Enter a string : ”)
print(“String in reverse order is”)
length = len(str1)
for a in range(-1, -(length+1), -1):
print(str1[a])

Output
Enter a string : hello
String in reverse order is
o
l
l
e
h
String Operators- There are 2 operators that can be used to work uponstrings + and *.

1. Concatenation + (it is used to join two strings)


Like - “tea” + “pot” will result into “teapot”
Like- “1” + “2” will result into “12”
Like – “123” + “abc” will result into “123abc”

2. Replication * (it is used to replicate the string)


like - 5*”@” will result into “@@@@@”
Like - “go!” * 3 will result in “go!go!go!”
Membership Operators in Strings- 2 membership operators work with strings that are in and not in.
To understand the working of these operators, look at the given examples -
• in operator results into True or False. Like-
“a” in “Sanjeev” will result in True. “ap” in “Sanjeev” will result in False.
• not in operator also results in True or False. Like-
“ap” not in “Sanjeev” will result in True. “anj” not in “Sanjeev” will result in False.

String Comparison Operators


“a” == “a” True “abc”==“abc” True “a”!=“abc” True “A”==“a” False “abc” ==“Abc” False
‘a’<‘A’ False (because Unicode value of lower case is higher than upper case)

Characters Ordinal values

‘0’ to ‘9’ 48 to 57

‘A to ‘Z’ 65 to 90

‘a’ to ‘z’ 97 to 122


How to get Ordinal/Unicode Values?
>>>ord (‘A’) >>>char(97)
65 a
>>>ord(‘a’) >>>char(65)
97 A

Program that prints following pattern without using any nested loop
*
**
***
****
*****

str = '*'
pattern=''
for i in range(5):
pattern+=str
print(pattern)

Write a program that asks a user for a username and a code. Ensure that the user doesn’t use their username as a
part of their code.
uname = input("Enter User Name: ")
code = input("Enter code: ")
if uname in code:
print("Your code should not contain your username.")
print("Thank You !")
Output
Enter User Name: Kode
Enter code: myKodeworld
Your code should not contain your username.
Thank You !

String Slicing

Built-in functions for string manipulations-

Method Description Example

len() Returns the length of the given string >>> str1 = 'Hello World!'
>>> len(str1)
12

title() Returns the string with first letter of every word in >>> str1 = 'hello WORLD!'
the string in uppercase and rest in lowercase >>> str1.title()
'Hello World!'

lower() Returns the string with all uppercase letters >>> str1 = 'hello WORLD!'
converted to lowercase >>> str1.lower()
'hello world!'

upper() Returns the string with all lowercase letters >>> str1 = 'hello WORLD!'
converted to uppercase >>> str1.upper()
'HELLO WORLD!'

count(str, start, end) Returns the number of times substring str occurs >>> str1 = 'Hello World! Hello Hello'
in the given string. If we do not give start index >>> str1.count('Hello',12,25)
and end index then searching starts from index 0 2
and ends at length of the string >>> str1.count('Hello')
3

find(str,start, end) Returns the first occurrence of an index of >>> str1 = 'Hello World! Hello Hello'
substring str occurring in the given string. If we do >>> str1.find('Hello',10,20)
not give start and end then searching starts from 13
index 0 and ends at length of the string. If the >>> str1.find('Hello',15,25)
substring is not present in the given string, then 19
the function returns -1 >>> str1.find('Hello')
0
>>> str1.find('Hee')
-1
index(str, start, end) Same as find() but raises an exception if the >>> str1 = 'Hello World! Hello Hello'
substring is not present in the given string >>> str1.index('Hello')
0
>>> str1.index('Hee')
ValueError: substring not found

endswith() Returns True if the given string ends with the >>> str1 = 'Hello World!'
supplied substring otherwise returns False >>> str1.endswith('World!')
True
>>> str1.endswith('!')
True
>>> str1.endswith('lde')
False

startswith() Returns True if the given string starts with the >>> str1 = 'Hello World!'
supplied substring otherwise returns False >>> str1.startswith('He')
True
>>> str1.startswith('Hee')
False

isalnum() Returns True if characters of the given string are >>> str1 = 'HelloWorld'
either alphabets or numeric. If whitespace or >>> str1.isalnum()
special symbols are part of the given string or the True
string is empty it returns False >>> str1 = 'HelloWorld2'
>>> str1.isalnum()
True
>>> str1 = 'HelloWorld!!'
>>> str1.isalnum()
False

islower() Returns True if the string is non-empty and has all >>> str1 = 'hello world!'
lowercase alphabets, or has at least one >>> str1.islower()
character as lowercase alphabet and rest are True
non-alphabet characters >>> str1 = 'hello 1234'
>>> str1.islower()
True
>>> str1 = 'hello ??'
>>> str1.islower()
True
>>> str1 = '1234'
>>> str1.islower()
False
>>> str1 = 'Hello World!'
>>> str1.islower()
False

isupper() Returns True if the string is non-empty and has all >>> str1 = 'HELLO WORLD!'
uppercase alphabets, or has at least one >>> str1.isupper()
character as uppercase character and rest are True
non-alphabet characters >>> str1 = 'HELLO 1234'
>>> str1.isupper()
True
>>> str1 = 'HELLO ??'
>>> str1.isupper()
True
>>> str1 = '1234'
>>> str1.isupper()
False
>>> str1 = 'Hello World!'
>>> str1.isupper()
False
isspace() Returns True if the string is non-empty and all >>> str1 = ' \n \t \r '
characters are white spaces (blank, tab, newline, >>> str1.isspace()
carriage return) True
>>> str1 = 'Hello \n'
>>> str1.isspace()
False

istitle() Returns True if the string is non-empty and title >>> str1 = 'Hello World!'
case, i.e., the first letter of every word in the string >>> str1.istitle()
in uppercase and rest in lowercase True
>>> str1 = 'hello World!'
>>> str1.istitle()
False

lstrip() Returns the string after removing the spaces only >>> str1 = ' Hello World! '
on the left of the string >>> str1.lstrip()
'Hello World! '

rstrip() Returns the string after removing the spaces only >>> str1 = ' Hello World! '
on the right of the string >>> str1.rstrip()
' Hello World!'

strip() Returns the string after removing the spaces both >>> str1 = ' Hello World! '
on the left and the right of the string >>> str1.strip()
'Hello World!'

replace(oldstr, newstr) Replaces all occurrences of old string with the >>> str1 = 'Hello World!'
new string >>> str1.replace('o','@')
'Hell@ W@rld!'
>>> str1 = 'Hello World!'
>>> str1.replace('World','Country')
'Hello Country!'
>>> str1 = 'Hello World! Hello'
>>> str1.replace('Hello','Bye')
'Bye World! Bye'

join() Returns a string in which the characters in the >>> str1 = ('HelloWorld!')
string have been joined by a separator >>> str2 = '-' #separator
>>> str2.join(str1)
'H-e-l-l-o-W-o-r-l-d-!'

partition() Partitions the given string at the first occurrence of >>> str1 = 'India is a Great Country'
the substring (separator) and returns the string >>> str1.partition('is')
partitioned into three parts. ('India ', 'is', ' a Great Country')
1. Substring before the separator >>> str1.partition('are')
2. Separator ('India is a Great Country',' ',' ')
3. Substring after the separator
If the separator is not found in the string, it returns
the whole string itself and two empty strings

split() Returns a list of words delimited by the specified >>> str1 = 'India is a Great Country'
substring. If no delimiter is given then words are >>> str1.split()
separated by space. ['India','is','a','Great', 'Country']
>>> str1 = 'India is a Great Country'
>>> str1.split('a')
['Indi', ' is ', ' Gre', 't Country']
Difference between partition() and string()-

Write a program that reads a line and prints its statistics like:
Number of uppercase:
Number of lowercase:
Number of alphabets:
Number of digits:

line = input("Enter a line:")


lowercount = uppercount=0
digitcount = alphacount=0
for a in line:
if a.islower():
lowercount += 1
elif a.isupper():
uppercount += 1
elif a.isdigit():
digitcount += 1
if a.isalpha():
alphacount += 1
print("Number of uppercase letters:", uppercount)
print("Number of lowercase letters:", lowercount)
print("Number of alphabets:", alphacount)
print("Number of digits:", digitcount)

Output:
Enter a line:Hello 123, ZIPPY zippy Zap
Number of uppercase letters: 7
Number of lowercase letters: 11
Number of alphabets: 18
Number of digits: 3

You might also like