Learn Python 3 Strings: Escaping Characters in A String
Learn Python 3 Strings: Escaping Characters in A String
Strings
str = 'yellow'
str[1] # => 'e'
str[-1] # => 'w'
str[4:6] # => 'ow'
str[:4] # => 'yell'
str[-3:] # => 'low'
Iterate String
To iterate through a string in Python, “for…in” notation is
used.
str = "hello"
for c in str:
print(c)
# h
# e
# l
# l
# o
`len()’ Built-in Function in Python
In Python, the built in function len() calculates the length
of objects. It can be used to compute the length of strings,
lists, sets, and other countable objects!
length = len("Hello")
print(length)
# output: 5
String concatenation
To combine the content of two strings into a single string,
Python provides the + operator. This process of joining
strings is called concatenation.
IndexError
When indexing into a string in Python, if you try to access
an index that doesn’t exist, an IndexError is generated. For
example, the following code would create an IndexError :
fruit = "Berry"
indx = fruit[6]
Lower
In Python, the string method .lower() returns a string with
all uppercase characters converted into lowercase.
.lower() does not take any input arguments.
# welcome to chili's
String replace
The .replace() method is used to replace the occurence of
the rst argument with the second argument within the
string.
fruit = "Strawberry"
print(fruit.replace('r', 'R'))
# StRawbeRRy
dinosaur = "T-Rex"
print(dinosaur.upper())
# Prints T-REX in the console.
The .join() String Method in Python
In Python, the .join() method can be used to concatenate
a list of strings together to create a new string joined with
the desired delimiter.
# An example of a .join()
x = "-".join(["Codecademy", "is", "awesome"])
# prints "Codecademy-is-awesome"
print(x)