Files
LearnPython/LearnTheBasics/6_BasicStringOperations.py
2024-09-13 15:12:25 +02:00

70 lines
2.5 KiB
Python

#Strings are bits of text. They can be defined as anything between quotes:
astring = "Hello world!"
astring2 = 'Hello world!'
astring = "Hello world!"
print("single quotes are ' '")
print(len(astring))
print(f"Location of the letter 'o' in '{astring}':",astring.index("o")) #First instance of the letter o
print(f"Location of the letter 'l' in '{astring}':",astring.index("l"), "\n") #First instance of the letter o
print(f"Amount of letter 'l' in '{astring}':",astring.count("l")) #amount of letters
print(f"Amount of letter 'o' in '{astring}':",astring.count("o"), "\n") #amount of letters
#specified characters ofa string:
print(f"specific characters '[3:7]' in '{astring}':",astring[3:7])
print(f"specific characters '[3:7:2]' in '{astring}':",astring[3:7:2]) #This prints the characters of string from 3 to 7 skipping one character. This is extended slice syntax. The general form is [start:stop:step].
print(f"specific characters '[::-1]' in '{astring}':",astring[::-1], "\n")
print(f"Capitalised version of '{astring}':",astring.upper())
print(f"Lowercase version of '{astring}':",astring.lower())
#true false values
print(astring.startswith("Hello"))
print(astring.endswith("asdfasdfasdf"))
#plitting the texts into a list
afewwords = astring.split(" ")
print(afewwords)
# Exercise
# Try to fix the code to print out the correct information by changing the string.
s = "Strings are awesome!"
# Length should be 20
print("Length of s = %d" % len(s))
# First occurrence of "a" should be at index 8
print("The first occurrence of the letter a = %d" % s.index("a"))
# Number of a's should be 2
print("a occurs %d times" % s.count("a"))
# Slicing the string into bits
print("The first five characters are '%s'" % s[:5]) # Start to 5
print("The next five characters are '%s'" % s[5:10]) # 5 to 10
print("The thirteenth character is '%s'" % s[12]) # Just number 12
print("The characters with odd index are '%s'" %s[1::2]) #(0-based indexing)
print("The last five characters are '%s'" % s[-5:]) # 5th-from-last to end
# Convert everything to uppercase
print("String in uppercase: %s" % s.upper())
# Convert everything to lowercase
print("String in lowercase: %s" % s.lower())
# Check how a string starts
if s.startswith("Str"):
print("String starts with 'Str'. Good!")
# Check how a string ends
if s.endswith("ome!"):
print("String ends with 'ome!'. Good!")
# Split the string into three separate strings,
# each containing only a word
print("Split the words of the string: %s" % s.split(" "))