In: Computer Science
Manipulating Strings
Manipulating strings are an important part of programming. When I first started I had quite a few assignments on just taking the strings apart and doing different manipulations to them. This helped me understand programming logic and ended up helping me a lot with future database programs. String manipulations can be done in programming, database, and reports which make it essential to know.
Class, have you been practicing some string manipulations? Any tips or tricks?
Dealing with Python Code language: Any enlightenment on this subject would help not just with the discussion question but to better understand this topic.
Thanks,
#-------- strings.py -----------
'''
-> A String is a sequence of characters
-> Strings can have any number of characters or just an empty string ""
-> in python whatever in between a pair of quotes(",') is a string.
-> spaces are also considered as character and it also have index for it.
Strings in python are immutable means you cannot modify them.
we will discuss them first we have to know how to create and access strings in python.
'''
#Creation of a string.
#put the string what you want in quotes, if your string has both the quotes
#use backslash(\) followed by quote you want
s = "Hello World"
print("\nString s:",s)
#accessing string
#to access single character use [ind] to get char at ind position.
#index starts from 0 to length of string -1.
#below statement prints the char at 0th index of the string s.
print("\nChar at 0th Index:",s[0])
'''
to access a string with range use slice operator [startIndex:endIndex] after the string variable name.
where startIndex is the starting index (inclusive) of the sub string wanted
and endIndex(excluded) is the end of the sub string position.
both startIndex and endIndex are optional
-> if startIndex is not given then it considers from index 0(starting index of the string)
-> if endIndex is not given then it considers the length of the string
below statement retries sub string from index 2 to 7 -> which returns "can't"
'''
print("\nSub string from index 2 to 7(exclusive):",s[2:7])
print("\nString using slicing starting to ending:",s[:])
print("\nString using slicing index 2 to ending:",s[2:])
print("\nString using slicing first 10 chars:",s[:10])
#Now you can't modify the string because python strings are immutable.
#below statment tries to modify the string , in doing so an exception will
#be thrown which will be caught in except section.
try:
s[0] = "I"
print("Successfully Modified String S: ",s)
except Exception as e:
print("\nException occured:",e)
#Sum String Manipulation Functions
#len() function takes an parameter of type string,array,list which are like arrays.
#returns the length of the parameter passed.
print("\nLength of String",s,"is:",len(s))
#finding a sub string in the string.
'''
There are two methods to find a sub string in python
1) find()
2) index()
1) find()
-> this method takes an argument of type string and returns the starting occurance index of it
-> if not found returns -1
called using s.find("sub string")
2) index()
-> this method takes an argument of type string and returns the starting occurance index of it
-> if not found raises an exception.
called using s.index("sub string")
'''
print("\nFinding sub string using find()")
print("index of llo in String",s,s.find("llo"))
print("index of x in String",s,s.find("x"))
print("\nFinding sub string using index()")
print("index of llo in String",s,s.index("llo"))
try:
print("index of x in String",s,s.index("x"))
except Exception as e:
print("Exception Occured:",e)
#counting the number of occurances of a sub string in source string.
'''
-> count() method takes a parameter as string and returns the number of occurances
-> of parameter in the string called it.
-> Syntax: s.count("l")
'''
print("\nNumber of times 'o' occured in",s,"is:",s.count("o"))
print("\nNumber of times 'x' occured in",s,"is:",s.count("x"))
'''
-> since you can't modify the string how to manipulate it.
-> the solution is replace() method
-> replace() method :-> replace(old,new,count)
-> old is the sub string that want to replace.
-> new is the sub string that replaces the old string.
-> count is the number of times to replace the old string with new string (Optional parameter).
-> if count not specified all the occurances of old is replaced by new.
-> replace method returns the replaces string and using that string we can do programming.
'''
print("\nReplacing every o to O in",s)
s = s.replace("o","O")
print("Replaced string",s)
print("\nReplacing first occurance of l to L in",s)
s = s.replace("l","L",1)
print("Replaced string",s)
#convertion case
#lower() method converts the string into lower case.
#upper() method converts the string into upper case.
#title() method converts the string into title case.
print("\nConvertion of one case to another")
print("Converting",s," to lower case",s.lower())
print("Converting",s," to upper case",s.upper())
print("Converting",s," to title case",s.title())
#split() method takes a string or a regular expression as parameter and returns an array
#of strings that are splitted by given parameter.
print("\nSplitting",s,"By","space",s.split(" "))
print("\nSplitting",s,"By","l",s.split("l"))
#strip() method removes the any leading whitespaces and ending whitespaces
#in the string.
st =" i am here "
print("\n",st,"After Striping on both sides->",st.strip(),"<-")
print("\n",st,"After Left Striping->",st.lstrip(),"<-")
print("\n",st,"After Right Striping->",st.rstrip(),"<-")
#These are the string manipulations and there are many more
#please like the answer.