String Literals

String literals in python are surrounded by either single quotation marks, or double quotation marks.

‘hello’ is the same as “hello”.

Strings can be output to screen using the print function. For example: print(“hello”).

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.

Example

Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!"
print(a[1])

 

Example

Substring. Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])

 

Example

The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

 

Leave a Reply

Your email address will not be published. Required fields are marked *