Added lecture 2026113
This commit is contained in:
parent
be356ccb59
commit
5b630435ae
27 changed files with 738 additions and 0 deletions
53
lecture20261103/lists02/lists07-join-split.py
Normal file
53
lecture20261103/lists02/lists07-join-split.py
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
#!/usr/bin/python3
|
||||
|
||||
# List join and split.
|
||||
|
||||
dogNames = [ "harry", "Shenanigans","katrina","Tanner","Yukon Jack", "Colorado","Mandy"]
|
||||
firstNames = ["edward","david", "Bob","mary","alice"]
|
||||
|
||||
# A simple loop to print every element in the list. The print() statement
|
||||
# automatically generates a newline at the end of each print.
|
||||
print("Print each name in the list.")
|
||||
print(firstNames)
|
||||
for aName in firstNames:
|
||||
print(aName)
|
||||
print("\n")
|
||||
|
||||
# Join all elements in the list to a single comma separated list
|
||||
print("Join the elements in the list to a single comma-separated list.")
|
||||
print(firstNames)
|
||||
nameString = ','.join(firstNames)
|
||||
print(nameString,"\n")
|
||||
|
||||
# Split all elements in the string into a list
|
||||
print("Split the elements in the string into a list.")
|
||||
print(nameString)
|
||||
myNewList = nameString.split(',')
|
||||
print(myNewList,"\n")
|
||||
|
||||
print("Now check membership in original list")
|
||||
print("Is david in myNewList ? ",'david' in myNewList)
|
||||
print("Exact match \n")
|
||||
|
||||
# Split all elements in the string into a list
|
||||
# Notice the effect of extra spaces.
|
||||
nameString2 = "edward ,david ,Bob ,mary ,alice"
|
||||
print("Split the elements in the string with extra space into a list.")
|
||||
print(nameString2)
|
||||
myNewList = nameString2.split(',')
|
||||
print(myNewList,"\n")
|
||||
|
||||
print("Now check membership in original list")
|
||||
print("Is david in myNewList ? ",'david' in myNewList)
|
||||
print("False match because 'david' does not equal 'david ' \n")
|
||||
|
||||
# Split a string into a list of characters
|
||||
sampleString = "This is a sample string of characters."
|
||||
listOfCharacters = list(sampleString)
|
||||
print("My new list is \n",listOfCharacters,"\nLength = ", len(listOfCharacters),"\n")
|
||||
|
||||
print("What happens if you reverse it, then reassemble the string?")
|
||||
listOfCharacters.reverse()
|
||||
print(listOfCharacters)
|
||||
myNewString = ''.join(listOfCharacters)
|
||||
print(myNewString)
|
||||
Loading…
Add table
Add a link
Reference in a new issue