0% found this document useful (0 votes)
26 views

1953685961-Strings in Python

Here are Python programs to solve the string problems: 1. To count vowels in a string: 2. To capitalize first and last letters: 3. To find length without spaces:

Uploaded by

ajey002hegde
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 views

1953685961-Strings in Python

Here are Python programs to solve the string problems: 1. To count vowels in a string: 2. To capitalize first and last letters: 3. To find length without spaces:

Uploaded by

ajey002hegde
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/ 29

Strings

● A string is a data structure in Python that represents a sequence of


characters
● It is an immutable data type, meaning that once you have created
a string, you cannot change it.
● Strings are used widely in many different applications, such as
○ Natural language Processing.
○ Regular expression.
○ Data mining.
○ Dictionaries.
○ Chatbot.
○ Machine translation.
Creating a String in Python
● Strings in Python can be created using single quotes or double quotes or
even triple quotes.
Index:
[0] [1] [2] [3] [4] [5]

p y t h o n
● Index can be variable,expression.
● It should be integer
ref:py_str1.py
● A segment of a
string is called a
slice.

● Selecting a slice is
similar to selecting
a character:
Exercise:
● Write a while loop that starts at the last character in the string and works
its way backwards to the first character in the string, printing each letter
on a separate line, except backwards.
● Given that fruit is a string, what does fruit[:] mean?
● Take the following Python code that stores a string: str =
'X-DSPAM-Confidence:0.8475' Use find and string slicing to extract the
portion of the string after the colon character and then use the float
function to convert the extracted string into a floating point number.
● Write a Python program to calculate the length of a string
Take the following Python code that stores a string: str =
'X-DSPAM-Confidence:0.8475' Use find and string slicing to extract the portion of the
string after the colon character and then use the float function to convert the extracted
string into a floating point number.

Ref:py_str3.py
● Strings are immutable

Solution: The best you can do is create a new string that is a variation on the original:
● This example concatenates a
new first letter onto a slice
of “python”.

● It has no effect on the


original string.
program counts the number of times the letter “a” appears in a string:

word = 'banana'
count = 0
for letter in word:
output Count of a’s:3
if letter == 'a':
count = count + 1
print(“count of a’s:”,count)
in operator

● The word in is a boolean operator that takes two strings and returns True if the first appears as a
substring in the second:

>>> 'o' in 'python'


True
>>> 'i' in 'python'
False
String comparison
word=input("enter string:")
enter string:banana
if word < 'banana': All right banana's
print('Your word,' + word + ', comes before banana.')
>>>
elif word > 'banana': enter string:Banana
Your word,Banana, comes before
print('Your word,' + word + ', comes after banana.')
banana.
else:
>>>
print("All right banana's") enter string:cat
Your word,ant, comes after banana.

Unicode of ‘b’=98 ‘B’=66 ‘c’=99


Exercises:

1. Write a program that accepts a string from user. Your program should count
and display number of vowels in that string.
2. Write a Python program to compare two strings and if the strings are equal,
True should be printed or else False should be printed.
3. Write a Python program to iterate through a string and check whether a
particular character is present or not. If present, true should be printed
otherwise, false should be printed.
>>> stuff = 'Hello world'
>>> type(stuff)
<class ‘str’>

>>> dir(stuff)
['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith' , 'expandtabs', 'find',
'format', 'format_map', 'index' , 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier' ,
'islower', 'isnumeric', 'isprintable', 'isspace' , 'istitle', 'isupper', 'join', 'ljust', 'lower',
'lstrip' , 'maketrans', 'partition', 'replace', 'rfind', 'rindex' , 'rjust', 'rpartition', 'rsplit',
'rstrip', 'split' , 'splitlines', 'startswith', 'strip', 'swapcase', 'title' , 'translate', 'upper',
'zfill']
capitalize()

>>> help(str.capitalize)
help(str.capitalize)
Help on method_descriptor:
capitalize(self, /)
Return a capitalized version of the string.

● More specifically, make the first character have upper case and the
rest lower case.
txt='hello and welcome to the world'
txt=’HELLO’
x=txt.capitalize()
x=txt.capitalize()
print(x)
print(x)
Output:
Output:
Hello and welcome to the world
Hello
upper()

>>> word='Banana'
>>> word='banana'
>>> >>>
newword=word.upper() newword=word.upper()
>>> print(newword)
>>> print(newword)
output:
output:
BANANA
BANANA
find():
String find() method returns the lowest index or first occurrence of the substring if
it is found in a given string. If it is not found, then it returns -1.

>>>
word='banana'
>>> word='banana'
>>> word.find('na') >>> word.find('na',3)
4
Output: >>>

2
strip():to remove white space (spaces, tabs, or newlines) from the beginning and end of a string
using the strip method:

line=' here we go'

>>> line.strip()
>>> line=' here we go '
>>> line.strip()
'here we go'
'here we go'
>>>
>>>
startswith()
>>> line='have a nice day'
>>> line.startswith('have')
True
>>> line=' have a nice day'
>>> line.startswith('have')
False
>>>
find()
>>> data = 'From [email protected] Sat Jan 5 09:14:16 2008'
>>> atpos=data.find('@')
>>> print(atpos)
21
>>> sppos = data.find(' ',atpos)
>>> print(sppos)
31
>>> host=data[atpos+1:sppos]
>>> print(host)
uct.ac.za
Format strings
● The format operator, % allows us to construct strings, replacing parts of the strings with
the data stored in variables.
● When applied to integers, % is the modulus operator.
● But when the first operand is a string, % is the format operator.
● The first operand is the format string, which contains one or more format sequences that
specify how the second operand is formatted. The result is a string.

>>> camels=42
>>> print( 'I have spotted %d camels.' % camels)
I have spotted 42 camels.
Exercise
● Python program to count no of vowels in a given string
○ Input: apple
○ output:2
● Python program to capitalize the first and last letter of the word
○ Input:apple
○ output:ApplE
● Python program to compute the length of the string without spaces
○ Input: python subject
○ output:13

You might also like