Featured

    Featured Posts

String in Python Part-1


String in Python


§  Strings are sequences of characters.

§  Python has a built-in string class named "str" with many handy features.

§  String literals can be enclosed by either double or single quotes.

§  Python strings are "immutable" which means they cannot be changed after they are created.

How to create a string and assign it to a variable

§  To create a string, put the sequence of characters inside either single quotes, double quotes, or triple quotes and then assign it to a variable

§  Even triple quotes can be used in Python but generally used to represent multiline strings and docstrings.
# all of the following are equivalent
my_string = 'Hello'
print(my_string)

my_string = "Hello"
print(my_string)

my_string = '''Hello'''
print(my_string)

# triple quotes string can extend multiple lines
my_string = """Hello, welcome to
           the world of Python"""
print(my_string)
Output:
Hello
Hello
Hello
Hello, welcome to
           the world of Python

How to access Character from the string:

§  There are two ways to access character from the string.
1.     By using Index
2.     By using slice operator

1. By using index
§  Characters in a string can be accessed using the standard [ ] 
§  In python string having both +ve and -ve index. i.e. we can access character from string using +ve and -ve index.

§  +ve index means going to forward direction (Left to Right)
§  -ve index means going to backward direction (Right to Left)

s="python"
print(s[0])        #output will be p
print(s[-6])       #output will be p
print(s[-1])       #output will be n


Take an input from the user and display each character and its index position.
s=input('enter string')
i=0
for x in s:
    print('The character {} present at positive index {}'.format(x,i))
    print('The character {} present at Negative index {}'.format(x,i-len(s)))
    i=i+1

#The Output will be
enter string
python
The character p present at positive index 0
The character p present at Negative index -6
The character y present at positive index 1
The character y present at Negative index -5
The character t present at positive index 2
The character t present at Negative index -4
The character h present at positive index 3
The character h present at Negative index -3
The character o present at positive index 4
The character o present at Negative index -2
The character n present at positive index 5
The character n present at Negative index -1

By Using Slice Operator:

s[beginindex:endindex:step]

§  from begin index to end-1 index and every time update by step
§  default value for begin index is zero.
§  default value for end index is length of string.

s[begin:end:step]

§  step value can be either +ve or -ve.
§  if +ve then it should be forward direction (Left to Right).

§  If -ve then it should be backward direction (Right to Left).

§  If +ve forward direction from begin to end-1.

§  if -ve backward direction from begin to end+1


s='python'
print(s[0:5])    # the output will be pytho
print(s[0:6])    # the output will be python
print(s[0:70])   # the output will be python
print(s[6:10])   # the output will be blank string becoz there is no specified  
                           substring in given range

print(s[0:6:2])  # the output will be pto
print(s[5:0:-1]) # the output will be nohty
print(s[2:8:-1]) # the output will be blank string
print(s[-1:-7:-1]) # the output will be nohtyp




v If you omit the first index, the slice starts at the beginning of the string. Thus, s[:m] and s[0:m] are equivalent:

s[:endindex]

s='python'
print(s[:4])#The Output Will be pyth
print(s[0:4])#The Output Will be pyth

v if you omit the second index as in s[n:], the slice extends from the first index through the end of the string. This is a nice, concise alternative to the more cumbersome s[n:len(s)]:

s[beginindex:]

   s='python'
print(s[2:])#The Output Will be thon
print(s[2:len(s)])#The Output Will be thon


v If you Omitting both indices return the original string.

s[:]

s='python'
print(s[:])#The Output Will be python
print(s[0: len(s)])#The Output Will be python

v If the first index in a slice is greater than or equal to the second index, Python returns an empty string.

s='python'
print(s[2:2])#The Output Will be empty string
print(s[4:2])#The Output Will be empty string

In forward Direction

§  default value for begin: 0
§  default value for end: length of the string
§  default value for step: 1

In backward direction
§  default value for begin index: -1
§  default value for end: -(length of string+1)

s='python'
print(s[-1::-1]) #the output will be nohtyp

# default value for end index is (len(s)+1)
# end:- -(6+1)=-7
# In Backward direction
# begin to end+1
# -1 to -7+1
# -1 to -6




Reversing a string

s=input('enter string')
rev=s[::-1]
print('Original String: ',s)
print('Reverse String: ',rev)

Output:
 enter string hello
Original String:  hello
Reverse String:  olleh

Check Given String is a Palindrome or Not?

def isPalindrome(s):
    rev=s[::-1]
    if s==rev:
        return True
    else:
        return False

s=input('enter string')
result=isPalindrome(s)
if result==True:
    print(s,' is a Palindrome String')
else:
    print(s,' is not a Palindrome String')

Output:
enter stringmadam
madam  is a Palindrome String

Iterating Through String

§  Using for loop we can iterate through a string.

for letter in 'Hello':
    print(letter)
Output
H
e
l
l
o

Write a python program for finding how many times any character occur in given string

s=input('enter string'
ch=input('enter letter for found')
count=0
for letter in s:
    if letter==ch:
        count+=1
print(count,'times',ch,' letters found in',s)
Output
enter stringhello
enter letter for foundl
2 times l letters found in hello



String Operators In Python


The + Operator

§  The + operator concatenates strings.
§  If we want to use + operator for str type then compulsory both arguments should be str type only otherwise we will get error.

a='hello'
b='world'
c='python'
d=10
print(a+b)#The Output Will be helloworld
print(a+b+c)#The Output Will be helloworldpython
print(a+d)
TypeError: can only concatenate str (not "int") to str

The * Operator

§  The * operator creates multiple copies of a string.

§  If we use * operator for str type then compulsory one argument should be int and other argument should be str type.

s='hello'
print(s*5)
#The Output Will be
hellohellohellohellohello


The in Operator

Checking Membership(String Contains):
§  We can check whether a string contains a given substring or not. Just use the in operator:
      str='python is a prog lang'
      print('python' in str)#the output will be True

Note: testing an empty string will always result in True:
print("" in "test")#the output will be True


s='python'
print('p'in s)          # The OutPut Will be True
print('po' in s)        # The OutPut Will be False
print('py' in s)        # The OutPut Will be True
print('po' not in s)    # The OutPut Will be True

Write a python program for check sub string exists within a string or not
main=input('enter main string')
subs=input('enter sub string to serach')
if subs in main:
    print(subs,"is found in",main)
else:
     print(subs,"sub string is not found in",main)

Write a python program for removal of vowels in given string
s=input('enter string')
vows=''
for ch in s:
    if ch in'aeiou':
        vows+=ch
print('Original String:- ',s)
print('After Removel of Consonaunt:- ',vows)
Output
enter stringhello
Original String:-  hello
After Removel of Consonaunt:-  eo


Write a python program for removal of consonant in given string
s=input('enter string')
cons=''
for ch in s:
    if ch not in'aeiou':
        cons+=ch
print('Original String:- ',s)
print('After Removel of Vowel:- ',cons)
Output
enter stringhello
Original String:-  hello
After Removel of Vowel:-  hll



Important Points:

§  Python provides many functions that are built-in to the interpreter and always available. Here are a few that work with strings:

Function
Description
chr()
Converts an integer to a character

ord()
Converts a character to an integer

len()
Returns the length of a string

str()
Returns a string representation of an object


chr(n)
§  Returns a character value for the given integer.

print(chr(65))# The output Will be A
print(chr(97))# The output Will be a
print(chr(57))# The output Will be 9

ord(c)
§  Returns an integer value for the given character.

print(ord('a'))# The output Will be 97
print(ord('A'))# The output Will be 65
print(ord('#'))# The output Will be 35

  len(s)
§  Returns the length of a string.

s='hello world'
print(len(s))#The Output will be 11

str(obj)
§  Returns a string representation of an object.

print(str(10))#The Output will be '10'
print(str(2.3))#The Output will be '2.3'
print(str((3+4j)))#The Output will be '(3+4j)'




author

Author Name

Author Description!

Get Free Email Updates to your Inbox!

Post a Comment

www.CodeNirvana.in

Powered by Blogger.

About

Site Links

Popular Posts

Translate

Total Pageviews