Strings in python are surrounded by either single quotation marks, or double quotation marks. 'hello' is the same as "hello".
1. String Literals
You can display a string literal with the print() function.
print("Hello")
print('Hello')
Multi-line Strings
You can assign a multiline string to a variable by using three quotes (either single or double).
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt."""
print(a)
2. String Indexing and Slicing
Like many other popular programming languages, strings in Python are arrays of bytes representing Unicode characters. You can access elements using square brackets.
Indexing
Note: The first character has index 0.
a = "Hello, World!"
print(a[1]) # Outputs 'e'
print(a[-1]) # Negative indexing gets the last character: '!'
Slicing
You can return a range of characters by using the slice syntax [start:end:step]. The end index is not included.
b = "Hello, World!"
print(b[2:5]) # "llo"
print(b[:5]) # "Hello" (Slice from start)
print(b[7:]) # "World!" (Slice to the end)
print(b[-5:-2]) # "orl" (Negative slicing)
3. String Concatenation
To concatenate, or combine, two strings you can use the + operator.
a = "Hello"
b = "World"
c = a + b
print(c) # "HelloWorld"
# Adding a space
c = a + " " + b
print(c) # "Hello World"
4. String Methods
Python has a set of built-in methods that you can use on strings. All string methods return new values. They do not change the original string.
upper(): Converts to upper case.lower(): Converts to lower case.strip(): Removes whitespace from the beginning or the end.replace(): Replaces a string with another string.split(): Splits the string into a list if it finds instances of the separator.join(): Joins the elements of an iterable to the end of the string.
a = " Hello, World! "
print(a.strip()) # "Hello, World!"
print(a.upper()) # " HELLO, WORLD! "
print(a.replace("H", "J")) # " Jello, World! "
print(a.split(",")) # [' Hello', ' World! ']
# Join Example
myList = ("John", "Peter", "Vicky")
x = "-".join(myList) # "John-Peter-Vicky"
5. String Formatting (f-strings, format())
We cannot combine strings and numbers simply by using the + operator. We have to use formatting.
F-Strings (Python 3.6+)
F-strings are the preferred way to format strings. Add an f in front of the string and put variables inside curly brackets {}.
age = 36
name = "John"
txt = f"My name is {name}, and I am {age}"
print(txt) # My name is John, and I am 36
The format() Method (Older way)
The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are.
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
6. Escape Characters
To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert.
For example, trying to put a double quote inside a double-quoted string:
# txt = "We are the so-called "Vikings" from the north." # ERROR
txt = "We are the so-called \"Vikings\" from the north." # Correct
Other useful escape characters:
\n: New Line\t: Tab\\: Backslash
Discussion
Loading comments...