Python Strings

Python Strings

Strings in python are surrounded by either single quotation marks, or double quotation marks. 'hello' is the same as "hello".

1. Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal sign and the string:

Basic String

a = "Hello"
print(a)

2. Multiline Strings

You can assign a multiline string to a variable by using three quotes (either """ or '''):

Multiline String

a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt."""
print(a)

3. Slicing Strings

You can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string. (Note: The first character has index 0).

Slicing Example

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

4. Modify Strings

Python has a set of built-in methods that you can use on strings.

String Methods

a = " Hello, World! "
print(a.strip()) // "Hello, World!"
print(a.upper()) // "  HELLO, WORLD!  "
print(a.replace("H", "J")) // "  Jello, World!  "

Exercise

?

Which method is used to remove whitespace from the beginning and end of a string?