Hour 13: Manipulating String

Example 13.1, Page No 210

In [3]:
str1=['A',' ','s','t','r','i','n','g',' ','c','o','n','s','t','a','n','t']
str2= "Another string constant"

i=0
for ch in str1:
    print ch,
print ""

for ch in str2:
    print ch,

print ""

#there is no concept of pointer in Python
ptr_str="Assign a string to a pointer"
for ele in ptr_str:
    print ele,
 A   s t r i n g   c o n s t a n t 
A n o t h e r   s t r i n g   c o n s t a n t 
A s s i g n   a   s t r i n g   t o   a   p o i n t e r

Example 13.2, Page No 212

In [12]:
str1=['A',' ','s','t','r','i','n','g',' ','c','o','n','s','t','a','n','t']
str2= "Another string constant"
ptr_str="Assign a string to a pointer"

print "The length of str1 is: %d bytes\n" % len(str1)
print "The length of str2 is: %d bytes\n" % len(str2)
print "The length of the string assigned to a pointer is: %d bytes" % len(ptr_str)
The length of str1 is: 17 bytes

The length of str2 is: 23 bytes

The length of the string assigned to a pointer is: 28 bytes

Example 13.3, Page No 213

In [22]:
str1="Copy a string"
str2=str1
str3=range(len(str1))

for i in range(len(str1)):
    str3[i]=str1[i]
    
str3[i]='\0'
print "The content of str2 using strcpy: %s" % str2
print "The contect of str3 without using strcpy: %s" % str3
The content of str2 using strcpy: Copy a string
The contect of str3 without using strcpy: ['C', 'o', 'p', 'y', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', '\x00']

Example 13.4, Page No 216

In [60]:
str1 = range(80)
delt=ord('a')-ord('A')

str1 = raw_input("Enter a string less than 80 characters: \n")
str1 = list(str1)
i=0
while(i!=len(str1)):
    if((str1[i]>='a') and (str1[i]<='z')):
        str1[i] = chr(ord(str1[i])-delt)
    i=i+1
print "The entered string is (in uppercase)\n"
print "".join(str1)
Enter a string less than 80 characters: 
This is a test.
The entered string is (in uppercase)

THIS IS A TEST.

Example 13.5, Page No 218

In [5]:
x=int(raw_input("Enter integer:"))
y=int(raw_input("Enter integer:"))
z=float(raw_input("Enter a floating-point number:"))
str1=raw_input("Enter a string:")
print "Here are what you've entered"
print "%d " % x,
print "%d " % y
print "%f " % z
print "%s " % str1
Enter integer:10
Enter integer:12345
Enter a floating-point number:1.234567
Enter a string:Test
Here are what you've entered
10  12345 
1.234567 
Test