Sunday, 27 August 2017

Python String & String Programs

Strings in Python:
=============
Strings are immutable sequence of characters.
Python accepts single, double and triple quotes.
There are actually 3 ways to define a string using either single, double or triple quotes:

text = 'The surface of the circle is 2 pi R = '
text = "The surface of the circle is 2 pi R = "
text = '''The surface of the circle is 2 pi R = '''
text = """The surface of the circle is 2 pi R = """

NOTE:
·      Strings in double quotes work exactly the same as in single quotes but allow to insert single quote character inside them.

·      The interest of the triple quotes (‘’’ or “””) is that you can specify multi-line strings.

·      Moreover, single quotes and double quotes can be used freely within the triple quotes:
""" a string with special character " and ' inside """

·      The ” and ‘ characters are part of the Python language; they are special characters. To insert them in a string, you have to escape them (i.e., with a \ chracter in front of them to indicate the special nature of the character). For instance:
text = " a string with escaped special character \", \' inside "

·      To include unicode, you must precede the string with the u character:
>>> u"\u0041"
A
unicode is a single character set used to represent 65536 different characters.

String input and output:
To output text (string) to the screen:
s = "hello world"
print(s)

To get text from keyboard:
[Python 3.x]
name = input("Enter name: ")
print(name)

[Python 2.x]
name = raw_input("Enter name: ")
print(name)

String Formatter:
In Python, the % sign lets you produce formatted output.
A quick example will illustrate how to print a formatted string:
>>> print("%s" % "some text")
"some text"

The syntax is simply:
string % values

If you have more than one value, they should be placed within brackets:
>>> print("%s %s" % ("a", "b"))

The string contains characters and conversion specifiers (here %s)
To escape the sign %, just double it:
>>> print "This is a percent sign: %%"
This is a percent sign:

String Operators:
The mathematical operators + and * can be used to create new strings:
t = 'This is a test'
t2 = t+t
t3 = t*3

and comparison operators >, >=, ==, <=, < and != can be used to compare strings.


String Comparison:
To test if two strings are equal use the equality operator (==).

#!/usr/bin/python
sentence = "The cat is brown"
q = "cat"
if q == sentence:
    print('strings equal')

To test if two strings are not equal use the inequality operator (!=)
#!/usr/bin/python
sentence = "The cat is brown"
q = "cat"
if q != sentence:
    print('strings equal')

String Index
Python indexes the characters of a string, every index is associated with a unique character. For instance, the characters in the string ‘python’ have indices:
String
String numbering
Characters in string

The 0th index is used for the first character of a string.
Try the following:

#!/usr/bin/python
s = "Hello Python"
print(s)      # prints whole string
print(s[0])   # prints "H"
print(s[1]) # prints "e"

String Slicing
:
Given a string s, the syntax for a slice is:
s[ startIndex : pastIndex ]
The startIndex is the start index of the string. pastIndex is one past the end of the slice.
NOTE:
If you omit the first index, the slice will start from the beginning. If you omit the last index, the slice will go to the end of the string. For instance:

#!/usr/bin/python
s = "Hello Python"
print(s[0:2]) # prints "He"
print(s[2:4]) # prints "ll"
print(s[6:])  # prints "Python"


Example:
=======
foo = "Monty Python's Flying Circus"

#Print the middle of foo- slice from the 7th-1 character end at the 15th-1 character
print foo[6:14]

#Use a slice to get the first six characters
print foo[:6]
#>>> Monty

#Slice after the first six characters of foo
print foo[6:]
#>>> Python's Flying Circus

#Print everthing in foo
print foo[:]
#>>> Monty Python's Flying Circus

#Every second character
print foo[0:27:2]
#>>> MnyPto' ligCru

#The last character of foo
print foo[-1]
#>>> s

#The last two characters of foo
print foo[-2:]
#>>> us

#Everything but the last seven charachers of foo
print foo[:-7]
#>>> Monty Python's Flying


Split() and Join() Methods in Python?

Split()  - Returns a list by seperating the elements based on the delimiter.  (Returns List)
-------
Example:
testString = "This,is,the,test,string"
testString.split(',')

Output:
['This', 'is', 'the', 'test', 'string']
Join()
------
str.Join() - Method returns a string This method returns a string.
Which is the concatenation of the strings in the sequence seq.
The separator between elements is the string providing this method.

e.x:
"".join(testString)

Output-> 'This,is,the,test,string'

e.x:
"-".join(testString)
Output-> 'T-h-i-s-,-i-s-,-t-h-e-,-t-e-s-t-,-s-t-r-i-n-g'

String-class:-
==========

>>default is UNICODE strings
>>single quoted    a='hello'
>>double quoted   a="hello"
>>triple quoted     a='''hello'''

Convert the string from UNICODE to bytes
a="hello" # Str
res=a.encode("utf-8")   # converts unicode string to bytes
ALITER
a=b"Hello" # bytes
hardware representation is in bytes

a=b"hello"
res=a.decode("utf-8")    # convert bytes to UNICODE STRING

String operations:-
a='hello world'
string length                    : len(a)
first element                    : a[0]     # indexing
last element                     : a[-1]
first 4 elems                    : a[:4]    # slicing
last 4 elems                     : a[-4:]
except first 4                   : a[4:]
except last 4                    : a[:-4]
except first 4 & last 4      : a[4:-4]
Alt elem                          : a[::2]
Alt elem                          : a[1::2]
reverse                            : a[::-1]
concate                           : "hello" + a
upper                              : a.upper()

Ex: Accept the string from the user as “sampling” and print as
sa-MPLI-ng
Sol:
res = input("Enter the string : ")
new = res[:2]+"-"+res[2:-2].upper()+"-"+res[-2:]
print(new)

Ex: Accept the string from the user as “sampling” and print as
S-nilpma-G
Sol:
res[0].upper() + "-" + res[1:-1][::-1].lower() + "-" + res[-1].upper()


Others functions:-
Search for a substring in a string ---->  
"hello" in mystr
                                          ---->  "hello" not in mystr
split the string                   -----> flst = a.split(delimiter)

a="192.168.1.125"

>> is "a" is string var - YES
>> what is delimiter    - "."
flst = a.split(".")
print(flst)
print(len(flst))
print(flst[0])
print(flst[-1])

find:-
------------
a.replace()
a.count()
a.index()
a.rindex()
a.find()
a.rfind()
a.rstrip()
a.lstrip()
a.strip()

----------------------------------------------------------------
a='sample data was added'

display the first word    a.split()[0]
display the last word     a.split()[-1]

display the first words last char  a.split()[0][-1]
display the last words first char  a.split()[-1][0]

a=10 20 30 40 50 60 70"
display first 4 fields

a.split()[0:4]

a="north 10,20,30,40"
display the first & last fields i.e 10 & 40

flst = a.split()[1].split(",")
print(flst[0],flst[-1])

import re
a="north 10,20,30,40"
flst = re.split("[\s,]",a)
ALITER

import re
a="sample-----hello-data----using-done"
b=re.sub("-+","-",a)
print(a)

a="north 10,20,30,40"

Things To Remember:
=================
1. How to convert a string to an int in python?
int(x [,base]) - Converts x to an integer. base specifies the base if x is a string.

2.How to convert a string to a long in python?
long(x [,base] ) - Converts x to a long integer. base specifies the base if x is a string.

3..How to convert a string to a float in python?
float(x) − Converts x to a floating-point number.

4.How will you convert a object to a string in python?

str(x) − Converts object x to a string representation.

5.How to convert a String to an object in python?
eval(str) − Evaluates a string and returns an object.

6.How to convert a string to a tuple in python?
tuple(s) − Converts s to a tuple.

7.How to convert a string to a list in python?
list(s) − Converts s to a list.

8.How to convert a string to a set in python?
set(s) − Converts s to a set.

9.How to convert an integer to hexadecimal string in python?
hex(x) − Converts an integer to a hexadecimal string.

10.How to capitalizes first letter of string?
capitalize() − Capitalizes first letter of string.

11.How to check in a string that all characters are digits?
isdigit() − Returns true if string contains only digits and false otherwise.

12.How to check in a string that all characters are alphanumeric?
isalnum() − Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.

13.How to check in a string that all characters are in lowercase?
islower() − Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.

14.How to check in a string that all characters are numerics?
isnumeric() − Returns true if a unicode string contains only numeric characters and false otherwise.

15.How to check in a string that all characters are whitespaces?
isspace() − Returns true if string contains only whitespace characters and false otherwise.

16.How to check in a string that it is properly titlecased?
istitle() − Returns true if string is properly "titlecased" and false otherwise.

17.How to check in a string that all characters are in uppercase?
isupper() − Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.

18.How will you get the length of the string?
len(string) − Returns the length of the string.

19.How will you remove all leading whitespace in string?
lstrip() − Removes all leading whitespace in string.

20.How to replaces all occurrences of old substring in string with new string?
replace(old, new [, max]) − Replaces all occurrences of old in string with new or at most max occurrences if max given.

21.How to remove all leading and trailing whitespace in string?
strip([chars]) − Performs both lstrip() and rstrip() on string.

22.How to get titlecased version of string?
title() − Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.

23. split(), sub(), subn() methods :
To modify the strings, Python’s “re” module is providing 3 methods. They are:
split() – uses a regex pattern to “split” a given string into a list.
sub() – finds all substrings where the regex pattern matches and then replace them with a different string
subn() – it is similar to sub() and also returns the new string along with the no. of
replacements.


24.Methods for matching and searching the occurrences of a pattern in a given text String ?
There are 4 different methods in “re” module to perform pattern matching. They are:
match() – matches the pattern only to the beginning of the String. search() – scan the string and look for a location the pattern matches findall() – finds all the occurrences of match and return them as a list
finditer() – finds all the occurrences of match and return them as an iterator.



String Related Programs:
===================
1. Find the sum of two numbers
a = input ("Enter the value of a : ")
b = input ("Enter the value of b : ")
#Note :By defult input takes a string
res = int(a) + int(b)
print("Final ans = ", res)

2. Remove the whitespaces from the string.
s = ‘aaa bbb ccc ddd eee’
''.join(s.split())

3. Write a Python program to check for a number at the end of a string
import re  
def end_num(string):  
    text = re.compile(r".*[0-9]$")  
    if text.match(string):  
        return True  
    else:  
        return False    
print(end_num('abcdef'))  
print(end_num('abcdef6'))


4. Write a Python program to find the substrings within a string
import re
text = 'Python exercises, PHP exercises, C# exercises'
pattern = 'exercises'
for match in re.findall(pattern, text):
    print('Found "%s"' % match)


5. Write a Python program to find the occurrence and position of the substrings within a string
import re
text = 'Python exercises, PHP exercises, C# exercises'
pattern = 'exercises'
for match in re.finditer(pattern, text):
    s = match.start()
    e = match.end()
    print('Found "%s" at %d:%d' % (text[s:e], s, e))


6.Write a Python program to match if two words from a list of words starting with letter 'P'.
import re
# Sample strings.
words = ["Python PHP", "Java JavaScript", "c c++"]

for w in words:
        m = re.match("(P\w+)\W(P\w+)", w)
        # Check for success
        if m:
            print(m.groups())


7. Write a Python program to separate and print the numbers of a given string
import re
# Sample string.
text = "Ten 10, Twenty 20, Thirty 30"
result = re.split("\D+", text)
# Print results.
for element in result:
    print(element)


8. Write a Python program to find all words starting with 'a' or 'e' in a given string
import re
# Input.
text = "The following example creates an ArrayList with a capacity of 50 elements. Four elements are then added to the ArrayList and the ArrayList is trimmed accordingly."
#find all the words starting with ‘a’ or ‘e’
list = re.findall("[ae]\w+", text)
# Print result.
print(list)


9. Write a Python program to separate and print the numbers and their position of a given string.
import re
# Input.
text = "The following example creates an ArrayList with a capacity of 50 elements. Four elements are then added to the ArrayList and the ArrayList is trimmed accordingly."
for m in re.finditer("\d+", text):
    print(m.group(0))
    print("Index position:", m.start())

10. Write a Python program to remove multiple spaces in a string
import re
text1 = 'Python      Exercises'
print("Original string:",text1)
print("Without extra spaces:",re.sub(' +',' ',text1))

11.Write a Python program to remove all whitespaces from a string
import re
text1 = ' Python Exercises '
print("Original string:",text1)
print("Without extra spaces:",re.sub(r'\s+', '',text1))


12. DocStrings
What is docstring in Python?
A Python documentation string is known as docstring, it is a way of documenting Python functions, modules and classes.

docstring is the documentation string for a function. It can be accessed by

function_name.__doc__

it is declared as:
def function_name():
"""your docstring"""
Writing documentation for your progams is a good habit and makes the code more understandable and reusable.

def printMax(x,y):
    '''print the maximum of two numbers.
        The two values must be integers..'''
    x = int(x)
    y = int(y)

    if x > y:
        print(x, 'is maximum')
    else:
        print(y, 'is maximum')

printMax(3,5)
print(printMax.__doc__)


13. Strings
name = 'manish'
if name.startswith('man'):
    print('Yes, the string starts with "man"')
if 'a' in name:
    print('Yes, it contains the string "a"')
if name.find('ish') != -1:
    print('Yes, it contains the string "ish"')
delimiter = '_*_'
mylist = ['USA','UK', 'India', 'Nepal']
print(delimiter.join(mylist))


14. Find if given string is palindrome
name = input("Enter the string: ")
if name[::] == name[::-1]:
    print(name, "is a palindrome")
else:
    print(name, "is not a palindrome")

15. Write a Python program that accepts a string and calculate the number of digits and letters
data = "Python 3.2"
d=l=0
for i in data:
    if i.isdigit():
        d += 1
    elif i.isalpha():
        l += 1
    else:
        pass
print("letters: ", l)
print("digits: ", d)


16. Write a Python program to reverse a string
def rev(str):
    res = str[::-1]
    return res

str = "1234abcd"
print(rev(str))

17.Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters
def string_test(s):
    d={"UPPER_CASE":0, "LOWER_CASE":0}
    for c in s:
        if c.isupper():
            d["UPPER_CASE"] += 1
        elif c.islower():
            d["LOWER_CASE"] += 1
        else:
            pass
    print("No of upper case chars: ", d["UPPER_CASE"])
    print("NO of lower case chars:", d["LOWER_CASE"])

string_test('The quick Brown Fox')


18. Multiline in python
s = '''This is a multi-line string.
This is the second line...'''
print(s)

s = 'This is a string. \
This continues the string.'
print(s)
#ALITER
print\
       (s)

19. What does the below mean?
s = a + ‘[‘ + b + ‘:’ + c + ‘]’
seems like a string is being concatenated. Nothing much can be said without knowing types of variables a, b, c. Also, if all of the a, b, c are not of type string, TypeError would be raised. This is because of the string constants (‘[‘ , ‘]’) used in the statement.

20.What would the following code yield?
word = 'abcdefghij'
print word[:3] + word[3:]

Ans: ‘abcdefghij’ will be printed.
This is called string slicing. Since here the indices of the two slices are colliding, the string slices are ‘abc’ and ‘defghij’. The ‘+’ operator on strings concatenates them. Thus, the two slices formed are concatenated to give the answer ‘abcdefghij’.

21. Program to Replace all Occurrences of ‘a’ with $ in a String:

string=input("Enter string:")
string=string.replace('a','$')
string=string.replace('A','$')
print("Modified string:")
print(string)

22.  Program to Remove the nth Index Character from a Non-Empty String

def remove(string, n): 
      first = string[:n]  
      last = string[n+1:] 
      return first + last
string=input("Enter the sring:")
n=int(input("Enter the index of the character to remove:"))
print("Modified string:")
print(remove(string, n))

23.  Program to Detect if Two Strings are Anagrams:
"An anagram is a type of word, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once. For example: orchestra can be rearranged into carthorse or cat can be rearranged into act.

s1=input("Enter first string:")
s2=input("Enter second string:")
if(sorted(s1)==sorted(s2)):
      print("The strings are anagrams.")
else:
      print("The strings aren't anagrams.")

Output:
1:
Enter first string:anagram
Enter second string:nagaram
The strings are anagrams.

2:
Enter first string:hello
Enter second string:world
The strings aren't anagrams.

24. Program to Form a New String where the First Character and the Last Character have been Exchanged

def change(string):
      return string[-1:] + string[1:-1] + string[:1]
string=input("Enter string:")
print("Modified string:")
print(change(string))

Output:
Case 1:
Enter string:abcd
Modified string:
dbca

25.Program to Count the Number of Vowels in a String.

string=input("Enter string:")
vowels=0
for i in string:
      if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'):
            vowels=vowels+1
print("Number of vowels are:")
print(vowels)

26.Program to Take in a String and Replace Every Blank Space with Hyphen

string=input("Enter string:")
string=string.replace(' ','-')
print("Modified string:")
print(string)

Output:
1:
Enter string:hello world
Modified string:
hello-world
2:
Enter string:apple orange banana
Modified string:
apple-orange-banana

27. Program to Calculate the Length of a String Without Using a Library Function

string=input("Enter string:")
count=0
for i in string:
      count=count+1
print("Length of the string is:")
print(count)

28.Program to Remove the Characters of Odd Index Values in a String

def modify(string): 
  final = ""  
  for i in range(len(string)): 
    if i % 2 == 0: 
      final = final + string[i] 
  return final
string=input("Enter string:")
print("Modified string is:")
print(modify(string))

Output:
1:
Enter string:hello
Modified string is:
hlo

2:
Enter string:checking
Modified string is:
cekn

29.Program to Calculate the Number of Words and the Number of Characters Present in a String
string=input("Enter string:")
char=0
word=1
for i in string:
      char=char+1
      if(i==' '):
            word=word+1
print("Number of words in the string:")
print(word)
print("Number of characters in the string:")
print(char)

Output:
1:
Enter string:Hello world
Number of words in the string:
2
Number of characters in the string:
11

2:
Enter string:I love python
Number of words in the string:
3
Number of characters in the string:
13

3. Enter string: abcdef abcdef manish bidsar
Number of words in the string:
4
Number of characters in the string:
27

30.Program to Take in Two Strings and Display the Larger String without Using Built-in Functions

string1=input("Enter first string:")
string2=input("Enter second string:")
count1=0
count2=0
for i in string1:
      count1=count1+1
for j in string2:
      count2=count2+1
if(count1<count2):
      print("Larger string is:")
      print(string2)
elif(count1==count2):
      print("Both strings are equal.")
else:
      print("Larger string is:")
      print(string1)


Output:
1.
Enter first string:Bangalore
Enter second string:Delhi
Larger string is:
Bangalore

2.
Enter first string: manish
Enter second string: abc
Larger string is:
Manish

31. Program to Count Number of Lowercase Characters in a String

string=input("Enter string:")
count=0
for i in string:
      if(i.islower()):
            count=count+1
print("The number of lowercase characters is:")
print(count)

Output:
1:
Enter string:Hello
The number of lowercase characters is:
4

2:
Enter string:AbCd
The number of lowercase characters is:
2

32.Program to Check if a String is a Palindrome or Not

string=input("Enter string:")
if(string==string[::-1]):
      print("The string is a palindrome")
else:
      print("The string isn't a palindrome")

Output:
1:
Enter string:malayalam
The string is a palindrome

2:
Enter string:manish
The string isn't a palindrome

33.Program to Calculate the Number of Upper Case Letters and Lower Case Letters in a String

string=input("Enter string:")
count1=0
count2=0
for i in string:
      if(i.islower()):
            count1=count1+1
      elif(i.isupper()):
            count2=count2+1
print("The number of lowercase characters is:")
print(count1)
print("The number of uppercase characters is:")
print(count2)

Output:
1.
Enter string: Manish Bidsar
The number of lowercase characters is:
10
The number of uppercase characters is:
2

2:
Enter string:HeLLo
The number of lowercase characters is:
2
The number of uppercase characters is:
3

34.Program to Check if a String is a Pangram or Not

from string import ascii_lowercase as asc_lower
def check(s):
    return set(asc_lower) - set(s.lower()) == set([])
strng=raw_input("Enter string:")
if(check(strng)==True):
      print("The string is a pangram")
else:
      print("The string isn't a pangram")


Output:
1:
Enter string:The quick brown fox jumps over the lazy dog
The string is a pangram

2:
Enter string:Hello world
The string isn't a pangram

35.Program to Accept a Hyphen Separated Sequence of Words as Input and Print the Words in a Hyphen-Separated Sequence after Sorting them Alphabetically

print("Enter a hyphen separated sequence of words:")
lst=[n for n in input().split('-')] 
lst.sort()
print("Sorted:")
print('-'.join(lst))

Output:
1:
red-green-blue-yellow
Sorted:
blue-green-red-yellow

2:
Enter a hyphen separated sequence of words:
Bangalore-hyderabad-delhi
Sorted:
Bangalore-delhi-hyderabad

36.Program to Calculate the Number of Digits and Letters in a String.

string=input("Enter string:")
count1=0
count2=0
for i in string:
      if(i.isdigit()):
            count1=count1+1
      count2=count2+1
print("The number of digits is:")
print(count1)
print("The number of characters is:")
print(count2)

Output:
1:
Enter string:Hello123
The number of digits is:
3
The number of characters is:
8

2:
Enter string:Abc12
The number of digits is:
2
The number of characters is:
5

37.Program to Form a New String Made of the First 2 and Last 2 characters From a Given String

string=input("Enter string:")
count=0
for i in string:
      count=count+1
new=string[0:2]+string[count-2:count]
print("Newly formed string is:")
print(new)

Output:
1:
Enter string:Hello world
Newly formed string is:
Held

2:
Enter string: manishbidsar
Newly formed string is:
Maar

38.Program to Count the Occurrences of Each Word in a Given String Sentence

string=input("Enter string:")
word=input("Enter word:")
a=[]
count=0
a=string.split(" ")
for i in range(0,len(a)):
      if(word==a[i]):
            count=count+1
print("Count of the word is:")
print(count)

Output:
1:
Enter string: abc abc abc abc ddd bbb ccc
Enter word: abc
Count of the word is:
4
2:
Enter string:orange blue red orange
Enter word:orange
Count of the word is:
2

39.Program to Check if a Substring is Present in a Given String

string=input("Enter string:")
sub_str=input("Enter word:")
if(string.find(sub_str)==-1):
      print("Substring not found in string!")
else:
      print("Substring found  in string!")

Output:
1:
Enter string:Hello world
Enter word:world
Substring in string!

2:
Enter string:Hello world
Enter word:apple

Substring not found in string!

For Quick Recap on Strings watch the below videos:


1 comment:

  1. Really good information to show through this blog. I really appreciate you for all the valuable information that you are providing us through your blog. python online course

    ReplyDelete

Note: only a member of this blog may post a comment.