Question

In: Computer Science

Manipulating Strings Manipulating strings are an important part of programming. When I first started I had...

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,

Solutions

Expert Solution

#-------- 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.


Related Solutions

This problem is about the java programming and contain two parts First part: a word that...
This problem is about the java programming and contain two parts First part: a word that reads the same forward and backward is called a palindrome, e.g., "mom", "dad", "racecar", "madam", and "Radar" (case-insensitive). Write a program called TestPalindrome, that asks the user for a word and prints whether the word is a palindrome or not. Hint: for a string called inStr, you can use inStr. toLowerCase() which returns a new string which is all in lower case letters. Use...
The following questions are on recursion in C++ Programming. I had some trouble with these questions,...
The following questions are on recursion in C++ Programming. I had some trouble with these questions, can you please help me? Thank you! Consider the following recursive function void funcEx8(int u, char v) //Line 1 { //Line 2 if (u == 0) //Line 3 cout << u << " "; //Line 4 else //Line 5 { //Line 6 int x = static_cast (v); //Line 7 if (v < 'A') //Line 8 v = static_cast (x + 1); //Line 9 else...
The first part of the question was answered and I was able to understand it, but...
The first part of the question was answered and I was able to understand it, but the second part of it was answered. Can you explain this part to me. Calculate the amount to be recorded for each item in the table below and enter the value in the associated cell. Round all numbers to the nearest whole number. Item Amount Building Leased equipment Land received from Club on Link's books Land received from Link on Club's books QUESTION 22...
Write your code inside of SecondProgrammingExam.java including all Part I: Given two strings, a and b,...
Write your code inside of SecondProgrammingExam.java including all Part I: Given two strings, a and b, create a bigger string made of the first char of a, the first char of b, the second char of a, the second char of b, and so on. Any leftover chars go at the end of the result. mixString("abc", "xyz") → "axbycz" mixString("Hi", "There") → "HTihere" mixString("xxxx", "There") → "xTxhxexre" Part II: Given an array of integers create an array of integers in...
Write your code inside of SecondProgrammingExam.java including all Part I: Given two strings, a and b,...
Write your code inside of SecondProgrammingExam.java including all Part I: Given two strings, a and b, create a bigger string made of the first char of a, the first char of b, the second char of a, the second char of b, and so on. Any leftover chars go at the end of the result. mixString("abc", "xyz") → "axbycz" mixString("Hi", "There") → "HTihere" mixString("xxxx", "There") → "xTxhxexre" Part II: Given an array of integers create an array of integers in...
Davidson Co. had the following transactions in 2017: - The business was started when it acquired...
Davidson Co. had the following transactions in 2017: - The business was started when it acquired $200,000 in cash from the issuance of common stock - The company purchased $900,000 of merchandise throughout the year - During the year, the Company sold merchandise for $1,200,000 (broken out as follows): - $ 520,000 Cash Sales - 380,000 Credit Card Sales - The Credit Card Company charges a 4% service fee - 300,000 Sales on Account $ 1,200,000 - The merchandise sold...
Explain why you believe sensitivity analysis is an important part of modelling using linear programming.
Explain why you believe sensitivity analysis is an important part of modelling using linear programming.
I have figured out the first part of this question in that there is no significant...
I have figured out the first part of this question in that there is no significant difference because 1.78<2.306. But this second part is confusing to me. Can you explain the formula I need to use? Thanks .Menstrual cycle lengths (days) in an SRS of nine women are as follows: {31, 28, 26, 24, 29, 33, 25, 26, 28}. Use this data to test whether mean menstrual cycle length differs significantly from a lunar month using a one sample t-test....
I have done the first part of this problem, but I cannot figure out the second...
I have done the first part of this problem, but I cannot figure out the second part. I know there are several different answers already posted on Chegg for this particular problem with different acceleration and time, but I need this one specifically, with a step by step solution. Again...just PART B....the answer to Part A is 201.72 A helicopter carrying Dr. Evil takes off with a constant upward acceleration of 4.20 m/s2. Secret agent Austin Powers jumps on just...
Suppose I had a budget of $150 dollars, what sort of relevant hardware / programming circuits...
Suppose I had a budget of $150 dollars, what sort of relevant hardware / programming circuits or circuit related devices could I purchase and invest in in order to make myself more competitive in today's electrical engineering job market? Initially I wanted to invest in arduino, but I heard arduino is outdated and not beneficial in today's market. What are similar more relevant technololgies that I can invest in as a recent electrical engineering graduate looking for an entry level...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT