Basic String Manipulation Flashcards
String Manipulation
- The process of being able to adopt or edit a string.
- We might do this in a program so that:
- we can ensure what the user has to enter is both easy for the user to understand and is also:
- then in the format we require it to be in.
String Concentation definition
- Simply refers to the process of bringing together (concatenating) two or more strings.
String Concatenation Example:
- In Python this is done using a +.
- In the example below we are requesting the
user input their date of birth.
- First they input their date, then month, then year.
- We are storing each of these as strings
- day = str(input(“Enter the day of your DOB - “))
- month = str(input(“Enter the month of your DOB - “))
- year = str(input(“Enter the year of your DOB - “))
- DOB = day + month + year
- print(DOB)
Splitting Strings at specific characters -
- Most often, when people enter their date of birth, they enter it by separating the different parts with a forward slash (/).
- In the example below, we are requesting the user enter their date of birth, separating each part with a /.
- We are then splitting this string up at each point where the user enters a /, and in this case storing each new string in a new variable:
- DOB = input(“Please enter your DOB in the format DD/MM/YYYY - “)
- day, month, year = DOB.split(“/“)
- print(day)
- print(month)
- print(year)
- Here we are requesting the user enter their DOB in the specified format.
- You will notice we haven’t put str before the input.
- If we don’t specify what data type we want to use when getting input, Python will automatically store it as a string.
Splitting At Specific Characters when you don’t know how many variables you need:
- We can store the new split strings inside a list.
- This means we have an open amount to store, and it doesn’t matter how much the user inputs.
- In the example below we are asking the user to enter their favourite words, separated by a space.
- In this case we don’t know how many words they might input:
- words = input(“Please enter your favourite words separated by a space - “)
- list_of_words = words.split(“ “)
print(list_of_words)
Splitting At Every Character:
- To do this, rather than using .split, we use the list function.
- This will create a list from the split
string. - Let’s take the example of creating a password.
- In the example below we are asking
the user to enter a word that is memorable to them. - We are then going to split it at each
individual character, and store each character in its own place in a list:
- word = input(“Enter a memorable word - “)
- list_of_letters = list(word)
- print(list_of_letters)