'This is some text, or a string'
"This is also text..."
Strings are a list of characters, what we call text.
In Python strings must be enclosed in quotation marks, either 'text' or "more text".
Python does not mind which you use, but it is important to know where you need both.
#Error due to the apostrophe
'This is Joe's computer.'
Sometimes you need to use both forms of quotation marks in a string.
#Use double quotations in this case
"This is Joe's computer."
#When you need to include quotations
"He said, 'My computer is broken.'"
#Python will also work this way round
'He said, "My computer is broken."'
Apostrophes:
Quotations:
print('''A Person
21 Some Road
Big Town
County
PO51 2CD''')
There are times when it is useful to display several lines of text...
This is done by enclosing the text in three quotation marks:
# Display an apostrophe
print('David\'s computer')
" ' / are all characters that have meaning in Python and sometimes you want to use them in your strings.
This is done by escaping them with the backslash (\) symbol:
# Display a quotation
print("\"To be or not to be...\"")
# Display a backslash
print('When you just need to show a backslash \\')
# Convert a string to an integer
string = input("Enter a value:")
num = int(string)
Input is always a string, so if you want to do calculations on user input you must convert the string to a number.
# Convert a string to an decimal
string = input("Enter a value:")
num = float(string)
# Convert a number to a string
string = str(number)
You may also need to convert a number to a string:
sentence = 'Some words'
length_sentence = len(sentence)
len(word)
To find the length of a string...
len(sentence) will hold the value 10, because a space is a character.
aString.upper()
>> WELCOME TO COMPUTING
aString = "welcome TO computing"
aString.lower()
aString.capitalize()
aString.title()
>> welcome to computing
>> Welcome to computing
>> Welcome To Computing
Note: capitalize (american spelling)
sentence = wordA + wordB + wordC
>> welcometocomputing
wordA = "welcome" wordB = "to" wordC = "computing"
sentence = wordA + " " + wordB + " " + wordC
>> welcome to computing
sentence = f"{wordA} {wordB} {wordC}"
>> welcome to computing
aString.strip(' ')
#Remove spaces from a string
aString = 'Welcome to Computing'
aString.strip(' ')
>> WelcometoComputing
#Remove C from a string
aString = 'Welcome to Computing'
aString.strip('C')
>> Welcome to omputing
aString[start:end]
#Show only Comp
aString = 'Welcome to Computing'
aString[11:15]
>> Comp
#Show from the fist c
aString = 'Welcome to Computing'
aString[3:]
>> come to Computing