Python Strings
Strings in python are surrounded by either single quotation marks, or double
quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
Example
print("Hello")
print('Hello')
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:
Example
a = "Hello"
print(a)
Strings are Arrays
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])
Looping Through a String/ Using a for loop to traverse a string:
Since strings are arrays, we can loop through the characters in a string, with
a for loop.
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
Operations on Strings-
String Concatenation
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)
Slicing
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
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
Slice From the Start
By leaving out the start index, the range will start at the first character:
Example
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
Slice To the End
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:])
String Comparison
The comparison operators also work on strings. To see if two strings are equal
you simply write a boolean expression using the equality operator.
Example:
word = "banana"
if word == "banana":
print("Yes, we have bananas!")
else:
print("Yes, we have NO bananas!")
word = "zebra"
if word < "banana":
print("Your word, " + word + ", comes before banana.")
elif word > "banana":
print("Your word, " + word + ", comes after banana.")
else:
print("Yes, we have no bananas!")
lower() Method
Example
txt = "Hello my FRIENDS"
x = txt.lower()
print(x)
replace() Method
txt = "I like bananas"
x = txt.replace("bananas", "apples")
print(x)
split() Method
Split a string into a list where each word is a list item:
txt = "welcome to the jungle"
x = txt.split()
print(x)
startswith() Method
txt = "Hello, welcome to my world."
x = txt.startswith("Hello")
print(x)
swapcase() Method
Make the lower case letters upper case and the upper case letters lower case:
txt = "Hello My Name Is PETER"
x = txt.swapcase()
print(x)
isalpha() Method
Check if all the characters in the text are letters:
txt = "CompanyX"
x = txt.isalpha()
print(x)
isalnum() Method
Check if all the characters in the text are alphanumeric:
txt = "Company12"
x = txt.isalnum()
print(x)
isnumeric() Method
Check if all the characters in the text are numeric:
txt = "565543"
x = txt.isnumeric()
print(x)
center() Method
Print the word "banana", taking up the space of 20 characters, with "banana"
in the middle:
txt = "banana"
x = txt.center(20)
print(x)
count() Method
Return the number of times the value "apple" appears in the string:
txt = "I love apples, apple are my favorite fruit"
x = txt.count("apple")
print(x)
Format Specifiers
Format specifiers in Python are codes used within string formatting operations
to define how a value should be presented. They control aspects like data type,
precision, alignment, and padding.
There are several methods for string formatting in Python that utilize format
specifiers:
• % operator (printf-style formatting): This older method uses
a % character followed by a type code (e.g., %d for integer, %s for
string, %f for float). Modifiers can be added for width, precision, and
alignment.
Example:
name = "Alice"
age = 30
print("Name: %s, Age: %d" % (name, age))
• str.format() method: This more modern and flexible method uses curly
braces {} as placeholders. Format specifiers are placed inside the braces
after a colon (e.g., {:.2f} for a float with two decimal places).
Example
pi = 3.14159
print("Value of Pi: {:.2f}".format(pi))
• F-strings (Formatted String Literals): Introduced in Python 3.6, f-strings
offer a concise and readable way to embed expressions inside string
literals. They also use curly braces and the same format specifier syntax
as str.format().
Example
item = "apple"
price = 1.25676
print(f"The {item} costs ${price:.2f}")
Common Format Specifiers (used with str.format() and f-strings):
• Type Specifiers:
• d: Integer
• f / F: Floating-point number
• s: String
• b: Binary
• o: Octal
• x / X: Hexadecimal (lowercase/uppercase)
• e / E: Scientific notation (lowercase/uppercase 'e')
• g / G: General format (chooses f or e based on magnitude)
• %: Percentage