Python Strings

Definition of String

You can use either single quotes or double-quotes to define strings in Python.

Cars = "Tesla cars"
print(Cars)
Tesla cars

However, when there are single quotes inside, you should only use double quotes or vice versa.

Test_1="Tesla's cars are great."
print(Test_1)

Test_2='He said "He loves Tesla cars."'
print(Test_2)
Tesla's cars are great.
He said "He loves Tesla cars."

Index and Slice Strings

You can index part of a string by using blockquotes, starting with 0. The following will print the letter “T.”

Cars = "Tesla cars"
print(Cars[0])
T

You can access part of the string by using colons. If without starting or ending with a number, Python assumes the first character or last character of the string. The substring includes the character at the start, but excludes the character at the end.

Cars = "Tesla cars"
print(Cars[0:3])
print(Cars[:5])
Tes
Tesla

When using a negative index number, Python returns the character starting from the end.

Cars = "Tesla cars"
print(Cars[-1]) 
s

Concatenate Strings

The following code shows how you can combine two strings together, and then print it out in Python.

part_1 = 'Good '
part_2 = 'Day'

parts_combined = part_1  + part_2 + '!'
print(parts_combined)
Good Day!

Use Variables in Python Strings

The following code shows how you can add a variable into a string and print it out in Python. Place the letter f before the quotation mark and put the brace around the variable name.

name = 'Bill'
message = f'Hello {name}'
print(message)
Hello Bill

Other Resource