String Manipulation
Let's do some string manipulation to make if statements even easier.name = input("What's your name? ")
if name == "David" or name == "david":
print("Hello Baldy!")
else:
print("What a beautiful head of hair!")
To the computer, " david", "dAviD", and "david" are completely different.
To simplify what the user typed in, we can add these functions to the end of the name of the variable:
.
lower = all letters are lower case
.upper = all letters are upper case
.title = capital letter for the first letter of every word
.capitalize = capital letter for the first letter of only the first word
The computer is converting everything to lowercase before it compares my if statements.
You need to type your if statement in lower case when you use .lower. The if statement needs to be written in upper case when you use .upper, etc.
name = input("What's your name? ")
if name.lower() == "david":
print("Hello Baldy!")
else:
print("What a beautiful head of hair!")
Adding .strip() removes any spaces on either side of the word.
name = input("What's your name? ")
if name.lower().strip() == "david":
print("Hello Baldy!")
else:
print("What a beautiful head of hair!")
myList = []
def printList():
print()
for i in myList:
print(i)
print()
while True:
addItem = input("Item > ").strip().capitalize()
if addItem not in myList:
myList.append(addItem)
printList()
Coding Challenge :-
Create a list of people's names. Ask for first and last name (surname) separately.Strip any extra spaces.
Store names in a capitalized version.
Create a new string using an fString that combines the tidied up version of the first name and tidied up version of the last name.
Add those new versions to a list.
Do not allow duplicates.
Each time you add a new name, you should print out the full list.
import os,time
yourName=[]
def prettyPrint():
os.system('clear')
print("Chart of All People")
print()
for i in yourName:
print(i)
time.sleep(1)
while True:
os.system('clear')
firstName=input("First Name please:").strip().capitalize()
lastName=input("Last Name please:").strip().capitalize()
name =f"{firstName} {lastName}"
if name in yourName:
print("already in the list")
elif name not in yourName:
yourName.append(name)
prettyPrint()
To do this, we use string slicing.
A string isn't just one big lump of text. In fact it's a list of individual characters.
By giving our program an index, we can specify which part of the string to chop out.
To slice a single character from a string, you use the index of that character in square brackets [] just like you'd use with a list!
To slice more than one character, you use two indices (yes that is the plural form of 'index'): the start character and one after your desired end character.
Leaving the first index blank defaults to 'start from index 0'.
Leaving the last index blank defaults to 'go to the end'.
The Secret Third Argument
Adding a third argument to the square brackets [] specifies the gap left between characters.
Try to print every other character in the word 'hello':
Can you print every third character in the whole string?
Using a negative number in the third argument can be super useful. It starts the slice from the end of the string instead of the beginning.
Split
split lets us split a string into a list of individual words by separating it at the space characters.
It stops printing too early
myString = "Hello there my friend."
print(myString[0])
# This code outputs the 'H' from 'Hello'
To slice more than one character, you use two indices (yes that is the plural form of 'index'): the start character and one after your desired end character.
myString = "Hello there my friend."
print(myString[6:11])
# This code outputs 'there'.
myString = "Hello there my friend."
print(myString[:11])
# This code outputs 'Hello there'.
myString = "Hello there my friend."
print(myString[12:])
# This code outputs 'my friend.'.
myString = "Hello there my friend."
print(myString[0:6:2])
# This code outputs 'Hlo' (every second character from 'Hello').
myString = "Hello there my friend."
print(myString[::3])
# This code outputs 'Hltrmfe!' (every third character from the whole string).
myString = "Hello there my friend."
print(myString[::-1])
#This code reverses the string, outputting '.dneirf ym ereht olleH'
myString = "Hello there my friend."
print(myString.split())
#This code outputs ['Hello', 'there', 'my', 'friend.']
Why is it printing 'Hell' instead of 'Hello'?
myString = "Hello there my friend."
print(myString[0:4])
myString = "Hello there my friend."
print(myString[0:5])
myString = "Hello there my friend."
print(myString[0:4:0])---- wrong code
The third argument should be at least 1.
CODING CHALLENGE
Ask the user to input their first & last names.Slice the first 3 letters of the first name.
Slice the first 3 letters of the last name (surname).
Join them together. Ideally change the case so that it looks good - think fStrings or .upper()/.lower(). This is the user's Star Wars first name.
Now ask the user for their mother's maiden name and the city where they were born. (Maiden name is the last name they had before they got married. If you are not sure, make up a last name.)
Combine the first two letters of the maiden name with the last 3 letters of the city to make the user's Star Wars last name. Remember, fStrings and .upper()/.lower().
Finally, print them both as part of a sentence.
Extra points for getting all the inputs with just one input command and the split function.
import os,time
starWars=[]
while True:
os.system('clear')
print("🌟Star Wars Name Generator🌟")
print()
print()
input_all= input("Input your first name., Input your last name,Input your Mother's name,Input your city name with a space in each word:").slipt().upper()
input1= input("Input your first name:").strip().upper()
input2= input("Input your last name:").strip().upper()
#output1= f"star wars first name is {input1[0:3]} {input2[0:3]}"
#print(output1)
input3= input("Input your Mother's name:").strip().upper()
input4= input("Input your city name:").strip().upper()
#output2= f"star wars second name is {input3[0:2]}{input4[0:3:-1]}"
#data = f"{input1[0:3]}{input2[0:3]} {input3[0:2]}{input4[-3:]}"
#print(f"{input1[0:3]}{input2[0:3]} {input3[0:2]}{input4[-3:]}")
#starWars.append(f"{input_all[0][0:3]}{input_all[1][0:3]} {input_all[2][0:2]}{input_all[3][-3:]}")
starWars.append(f"{input1[0:3]}{input2[0:3]} {input3[0:2]}{input4[-3:]}")
print(input_all)
print(starWars)
time.sleep(2)
More better version :-
print("STAR WARS NAME GENERATOR")
all = input("Enter your first name, last name, Mum's maiden name and the city you were born in").split()
first = all[0].strip()
last = all[1].strip()
maiden = all[2].strip()
city = all[3].strip()
name = f"{first[:3].title()}{last[:3].lower()} {maiden[:2].title()}{city[-3:].lower()}"
print(f"Your Star Wars name is {name}")
No comments:
Post a Comment