String
String
Example
print("Hello")
print('Hello')
Assigning a string to a variable is done with the variable name followed by an equal
sign and the string:
Example
a = "Hello"
print(a)
You can assign a multiline string to a variable by using three quotes:
Example
a = """UEH,
3I,
Example
a = ''' UEH,
3I,
Get the character at position 1 (remember that the first character has the position
0):
a = "Hello, World"
print(a[1]) #index
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
To check if a certain phrase or character is present in a string, we can use the keyword in.
Example
Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.
Example
Check if "expensive" is NOT present in the following text:
txt = "The best things in life are free!"
print("expensive" not in txt)
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.
Example
b = "Hello, World!"
print(b[2:5])
By leaving out the start index, the range will start at the first character:
Example
b = "Hello, World!"
print(b[:5])
By leaving out the end index, the range will go to the end:
Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Use negative indexes to start the slice from the end of the string:
Example
b = "Hello, World!"
print(b[-5:-2])
To concatenate, or combine, two strings you can use the + operator.
Example
Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c=a+b
print(c)
Example
To add a space between them, add a " ":
a = "Hello"
b = "World"
c=a+""+b
print(c)
count()
find()
isalnum()
isalpha()
isdigit()
islower()
isnumeric()
isupper()
lower()
replace()
split()
upper()
1
1
1
1
1