Discuss substrings, finds, concat
This commit is contained in:
parent
47803c2f54
commit
63d4fcdc15
|
@ -33,6 +33,47 @@ elif full_name.islower():
|
|||
print("Your name seems to have been entered in all lower case letters.")
|
||||
else:
|
||||
print("Your name seems to have been entered with both capital and lower case letters.")
|
||||
|
||||
print()
|
||||
|
||||
|
||||
# Python strings can be combined with "+". This is called "concatenation"
|
||||
str1 = "Hello"
|
||||
str2 = "World"
|
||||
full_str = str1 + " " + str2
|
||||
print(f"str1 = \"{str1}\"")
|
||||
print(f"str2 = \"{str2}\"")
|
||||
print(f"str1 + \" \" + str2 = \"{full_str}\"")
|
||||
print()
|
||||
|
||||
# Strings are simply a collection of characters (like but not limited to keyboard keys)
|
||||
# An "index" in a string means what character you are referring to. Strings start
|
||||
# at index zero (0) and count up by one for each character. This means the third
|
||||
# character in a string is index 2 (i.e. 0 1 2)
|
||||
|
||||
# A "slice" or "substring" of a string is just a smaller part of the whole string.
|
||||
# The syntax for a slice is string_variable[start:end:step]
|
||||
# Where:
|
||||
# start is the index of the first character you want to grab
|
||||
# if start is omitted it will start at zero/first character
|
||||
# if start is negative it will start that many characters from the end of the string
|
||||
# end is the index in the string for where you want to stop grabbing
|
||||
# if end is omitted it will grab everything to the end of the string
|
||||
# if end is negative it will end that many characters from the end of the string
|
||||
# step allows you to skip to every "step" character
|
||||
# (i.e. a step of 3 would mean get every third character)
|
||||
# if step is omitted it defaults to 1 (i.e. every character)
|
||||
my_string = "This Is Your Life In A Nutshell"
|
||||
# The use of \" here means we "escape" the quote.
|
||||
# This is how include a quote inside a string enclosed by quotes
|
||||
print(f"my_string = \"{my_string}\"")
|
||||
print("my_string[:4] =", my_string[:4])
|
||||
print("my_string[8:17] =", my_string[8:17])
|
||||
print("my_string[-8:] =", my_string[-8:])
|
||||
print("my_string[-5:-2] =", my_string[-5:-2])
|
||||
|
||||
# The "find()" method can be used to find one string inside another.
|
||||
# It will return:
|
||||
# -1 if the search pattern was not found
|
||||
# the index in the string where the pattern first starts
|
||||
# It will only find the first match
|
||||
if my_string.find("Life") != -1:
|
||||
print(f"\"{my_string}\" contains the string \"Life\"")
|
Loading…
Reference in New Issue
Block a user