What is a Python String?
Strings in python are a character or sequence of characters, enclosed in a pair of single or double quotes. For example: 'Test String'
or "Test String"
.
Python string literals are immutable, meaning once a string is created, it cannot be changed. String literals are also zero-base indexed (index starts at 0), similar to a list, and can be sliced.
A backslash can be used to escape special characters, and all string methods return the result as a new string.
This guide is designed to walk you through how to use Python strings efficiently, with clear, commented code samples.
- Create a string
- Printing strings
- Python string formatting
- When to use quotation marks
- Escape characters
- String operators
- Returning elements of a string
- How to modify a string
- How to iterate a string
- String comparison
- Python string functions
- Python string methods
How to Create a String
Strings can be created by assigning text contained in single or double quotes to a variable.
# Single and double quotes are both valid syntax a = 'single quote string' b = "double quote string" print(type(a)) print(type(b))
Output:
class 'str'
class 'str'
Printing Strings
print()
can be used to output strings to the console.
# Display 'TestString' on the screen print("TestString")
Output:
TestString
Python String Formatting
Before f-strings were introduced in Python 3.6, there were a couple of ways to format strings in Python. You could either use the format method with string.format()
, or use the %
operator.
f-strings made string formatting in Python a whole lot easier.
With f-strings, you can simply prefix the string with either f
or F
and reference variable names directly within the string, provided they were enclosed in curly brackets {}
.
name = "Dan" age = 30 f"{name} is {age} years old."
Output:
'Dan is 30 years old.'
Example 2: Multi-line f-string in Python 3
name = "Dan" age = 30 multi_line = ( f"{name} is " f"{age} years old." ) multi_line
Output:
'Dan is 30 years old.'
You can even call functions and expressions directly within the string, as f-strings are evaluated at runtime.
Example 3: Simple calculation in an f-stringf"{10-4}"
Output:
'6'
When to use quotation marks
Python supports three main types of quotation marks: single quotes, double quotes and triple quotes. But it’s not always easy to remember when to use each type and how many to use.
Single quotesSingle quotes can be used to enclose a string, or within a string that’s enclosed by double quotes if you want to include an apostrophe without using an escape character.
single_quotes = 'Test String' single_quotes = "Isn't this a string"Double quotes
Double quotes can be used to enclose strings. A double quote can also be included in a string that’s enclosed by single quotes, without using an escape character.
double_quotes = "Test String" double_quotes = 'Here is a double quote: "'Triple quotes
In some situations you will want to print strings on multiple lines, to make the text more readable to humans. This is possible by using tripe quotes '''
or triple double quotes """
.
""" Multi-line Test String """ ''' Another multi-line Test String '''
Escape Characters
When working with Python strings, a backslash \
is used as the escape character. This is used as a prefix to different characters to produce certain whitespace operations, or to turn a special character into an ordinary character.
An example of this is when you include a quotation mark in your string, in the same format as those used to wrap the string. E.g. 'Isn\'t this a valid string.'
Escape Sequence | Description |
---|---|
\t | Tab |
\n | New line |
\r | Carriage return |
\\ | Escape itself |
String Operators
Python strings can be manipulated using the following operators:
Operator | Operator Type | Example |
---|---|---|
+ | Concatenation | string1 + string2 |
* | Repetition | string1 * string2 |
[] | Slice | string1[0] |
[:] | Range Slice | string1[0:5] |
in | Membership | "s" in "Test" |
not in | Membership | "a" not in "Test" |
r | Raw String | r"A \n raw string" |
and | Logical | (a and b) |
or | Logical | (a or b) |
not | Logical | Not(a and b) |
Returning Elements of a String
Specific elements of a string can be accessed in two ways:
- Access a single element of a string. E.g.
string[index]
- Slice a string to create a substring. E.g.
string[start:stop:step]
# Access a single element of a string a = "TestString" print("a =", a) print("a[1] = ", a[1]) # Should return 'e' # Access a multiple elements of a string a = "TestString" print("a[1:4] = ", a[1:4]) # Should return 'est'
Output:
a = TestString
a[1] = e
a[1:4] = est
As with list slicing, the number following the first :
will not be included. String elements with indexes of 1, 2, and 3 will be displayed.
How to reverse a string using Python
To reverse a string in Python, you can use slicing and set the step to be a -1
.
# Create a test string string1 = "TestString" print("string1 =", string1) # Reverse the sequence order using indexes and a step of -1 string2 = string1[::-1] print("string1[::-1] =", string2)
Output:
string1[::-1] = gnirtStseT
How to Modify a String
Python strings are immutable, meaning their composition cannot be modified and you cannot delete a substring of characters. You can, however, assign a substring to a new variable, or delete the entire string.
# Create a test string string1 = "This is a test string." # Attempt to assign a new value to an index of string1 string1[0] = "A"
Output:
Traceback (most recent call last):
File "", line 2, in
TypeError: 'str' object does not support item assignment
How to Iterate a String
Python string iteration can be performed using a for
loop.
# Create a test string string1 = "TestString" print("string1 =", string1) # Iterate through the string, and only print a character if it's upper case for i in string1: if i.isupper(): print("Upper Case: ", i)
Output:
Upper Case: T
Upper Case: S
String Comparisons
Lexicographical comparison of python strings can be performed using the relational operators: >
, <
, >=
, <=
, ==
, !=
.
# Create two test strings string1 = "This is a test string." string2 = "Test is another test string." print("string1 =", string1) print("string2 =", string2) # Use relational operators to compare the two strings print("string1 > string2: ", string1 > string2) # TRUE print("string1 < string2: ", string1 < string2) # FALSE print("string1 >= string2: ", string1 >= string2) # TRUE print("string1 <= string2: ", string1 <= string2) # FALSE print("string1 == string2: ", string1 == string2) # FALSE print("string1 != string2: ", string1 != string2) # TRUE
Output:
string1 > string2: TRUE
string1 < string2: FALSE
string1 >= string2: TRUE
string1 <= string2: FALSE
string1 == string2: FALSE
string1 != string2: TRUE
Python String Functions
A number of in-built functions can be used when working with strings in Python. Listed below are some of the most useful:
len()The in-built len()
function can be useful for determining the length of a string.
Syntax: len(string)
# Create a test string string1 = "This is a test string." print("string1 =", string1) # Check the length of the string, using len() print("len(string1) =", len(string1)) # Check the length of an empty string print("len('') =", len(""))
Output:
string1 = This is a test string.
len(string1) = 22
len('') = 0
min()
When passed a string, the min()
function returns the letter that appears earliest in the alphabet. If the string contains whitespace, then this will be seen as less than 'a'.
Syntax: min(string)
# Create a test string with no whitespace string1 = "TestString" print("string1 =", string1) # Print the minimum value from string1 print("min(string1) =", ord(min(string1))) # Create a second test string, containing whitespace string2 = "Test String" print("\nstring2 =", string2) # Print the minimal value from string2 print("min(string2) =", ord(min(string2))) # Check what happens when min() is passed an empty string print("\nmin('') =", min(""))
Output:
string1 = TestString
min(string1) = 83
string2 = Test String
min(string2) = 32
Traceback (most recent call last):
File "", line 2, in
ValueError: min() arg is an empty sequence
In the example above, each test returns an integer representing the Unicode code point of the character. For string1
, 83 is the Unicode code point for 'e'. A ValueError
is thrown when min()
is passed an empty string.
When passed a string, the max()
function returns the letter that appears latest in the alphabet. Case insensitive.
Syntax: max(string)
# Create a test string with no whitespace string1 = "TestString" print("string1 =", string1) # Print the maximum value from string1 print("max(string1) =", ord(max(string1))) # Create a second test string, containing whitespace string2 = "Test String" print("\nstring2 =", string2) # Print the maximum value from string2 print("max(string2) =", ord(max(string2))) # Check what happens when max() is passed an empty string print("\nmax('') =", max(""))
Output:
string1 = TestString
max(string1) = 116
string2 = Test String
max(string2) = 116
Traceback (most recent call last):
File "", line 2, in
ValueError: max() arg is an empty sequence
In the example above, each test returns an integer representing the Unicode code point of the character. For string1
and string2
, 116 is the Unicode code point for 't'. A ValueError
is thrown when max()
is passed an empty string.
Python String Methods
Python supports a wide range of useful string methods. These allow you to perform tasks such as making text upper case, splitting a string based on a delimiter meter, and stripping any white space from around a piece of text.
Below, you'll find a complete guide to python string methods.
Method | Description |
---|---|
capitalize() | Capitalizes the first letter of a string. |
center() | Pads a string with the designated fillchar value, to fill the desired width . String is centered within the padding. |
count() | Counts how many times str occurs in a string. beg and end can also be specified if you only want to count the occurences of a substring within an index range of the main string. |
decode() | Decodes the string. |
encode() | Encodes the string. Setting errors to 'ignore' or 'replace' will suppress the ValueError that gets raised if the default of strict is preserved. |
endswith() | Boolean condition, which returns true if the string ends with suffix , or false if it doesn't. beg and end can also be specified if you only want to check within an index range of the main string. |
expandtabs() | Expand tabs in a string. Defaults to 8, or you can pass in a custom tabsize . |
find() | If str exists in string, return the first index that it occurs at, otherwise return -1. beg and end can also be specified if you only want to check within an index range of the main string. |
index() | Works the same way as find() , but raises an exception instead of returning -1 if str is not found. |
isalnum() | Returns true if all characters in string are alphanumeric, otherwise false. String must contain at least 1 character. |
isalpha() | Returns true if all characters in string are alphabetic, otherwise false. String must contain at least 1 character. |
isdecimal() | Returns true if all characters in a unicode string are decimal, otherwise false. |
isdigit() | Returns true if all characters in string are digits, otherwise false. String must contain at least 1 character. |
islower() | Returns true if all characters in string are all lower case, otherwise false. String must contain at least 1 cased character. |
isnumeric() | Returns true if all characters in a unicode string are numeric, otherwise false. |
isspace() | Returns true if string is entirely whitespace, otherwise false. |
istitle() | Returns true if string is 'titlecased', otherwise false. |
isupper() | Returns true if all characters in string are all upper case, otherwise false. String must contain at least 1 cased character. |
join() | Returns a string concatenated with the elements of an iterable. Separator string must be specified. Inverse of split() . |
ljust() | Pads a string with the designated fillchar value, to fill the desired width . String is left justified within the padding. |
lower() | Returns the string converted to lower case. |
lstrip() | Removes an whitespace from the left of the string. |
maketrans() | Creates a translation table, mapping old values to new values. This is then used for character replacement in the translate() method. |
replace() | Replaces a string with another string. |
rjust() | Pads a string with the designated fillchar value, to fill the desired width . String is right justified within the padding. |
rstrip() | Removes any whitespace from the right of the string. |
split() | Splits the string on occurrences of str . Splits on space by default. Returns list of substrings. |
startswith() | Boolean condition, which returns true if the string starts with str , or false if it doesn't. beg and end can also be specified if you only want to check within an index range of the main string. |
strip() | Removes any whitespace from the left and right of a string. |
swapcase() | Inverts case for all cased characters in the string. |
upper() | Returns the string converted to upper case. |
The capitalize()
method returns a copy of the word, with the first character capitalized.
Syntax: capitalize()
# Create a test string string1 = "test string" # Use capitalize() to make the first character upper case print("'test string'.capitalize() =", string1.capitalize()) string1 = " " +string1 # Use capitalize() on a space to check for errors print("' test string'.capitalize() =", string1.capitalize()) string1 = "0" +string1 # Use capitalize() on a zero to check for errors print("'0 test string'.capitalize() =", string1.capitalize())
Output:
'test string'.capitalize() = Test string
' test string'.capitalize() = test string
'0 test string'.capitalize() = 0 test string
center()
The center()
method will center a string within a given width of characters. If the string it's applied to is shorter than the specified width, a padding character can be specified with fillchar
.
Padding will be applied equally to the left and right of the string. If the number of padding characters is odd, the majority will apply on the left. E.g. 'test'.center(11, "0") = '0000test000'
. If no fillchar
value is supplied, space will be used by default.
Syntax: center(width[,fillchar])
# Create a test string string1 = "TestString" print("string1 =", string1) # Use center(10, "0") to confirm the string is unchanged (length=10) print("string1.center(10, '0') =", string1.center(10, "0")) # Use center(16, "0") to confirm the string is centered and padded with '0' print("string1.center(16, '0') =", string1.center(16, "0")) # Use center(15, "0") to check center with uneven padding value print("string1.center(15, '0') =", string1.center(15, "0")) # Use center(15) to check center with uneven padding, using default white space print("string1.center(15) =", "[" + string1.center(15) + "]")
Output:
string1 = TestString
string1.center(10, '0') = TestString
string1.center(16, '0') = 000TestString000
string1.center(15, '0') = 000TestString00
string1.center(15) = [ TestString ]
count()
The count()
method returns the number of non-overlapping occurrences of a substring in the string. Specifying the beg>
and end
indexes will restrict the count()
to a section of the string.
Syntax: count(str[, beg=0][, end=len(string)])
# Create a test string string1 = "This is a test string." print("string1 =", string1) # Count how many times 'i' appears print("Times 'i' appears =", string1.count("i")) # Count how many times 'i' appears after index 5 print("Times 'i' appears after [5] =", string1.count("i", 5)) # Count how many times 'i' appears after index 3 but before index 15 print("Times 'i' appears after [5] but before [15] =", string1.count("i", 5, 15)) # Check what happens when a str value is passed in that doesn't exist in the string print("Times 'x' appears =", string1.count("x"))
Output:
string1 = This is a test string.
Times 'i' appears = 3
Times 'i' appears after [5] = 2
Times 'i' appears after [5] but before [15] = 1
Times 'x' appears = 0
endswith()
The endswith()
method can be used to check if a string ends with a specific character. Returns Boolean.
Syntax: endswith(suffix[, beg=0][, end=len(string)])
# Create a test string string1 = "This is a test string." print("string1 =", string1) # Check if string1 endswith('.') print("string1.endswith('.') =", string1.endswith(".")) # Check if string1 endswith('z') print("string1.endswith('z') =", string1.endswith("z")) # Check if string1 endswith('.'). Start index = 5 print("string1.endswith('.', 5) =", string1.endswith(".", 5)) # Check if string1 endswith('.'). Start index = 5, end index = 10 print("string1.endswith('.', 5, 10) =", string1.endswith(".", 5, 10)) # Check if string1 endswith(' '). Start index = 5, end index = 10 print("string1.endswith(' ', 5, 10) =", string1.endswith(" ", 5, 10)) # Check what happens when a str value is passed in that doesn't exist in the string print("string1.endswith('z', 5, 10) =", string1.endswith("z", 5, 10)) # Check what happens when a start index is passed in that's too large print("string1.endswith('t', 30, 35) =", string1.endswith("t", 30, 35))
Output:
string1 = This is a test string.
string1.endswith('.') = True
string1.endswith('z') = False
string1.endswith('.', 5) = True
string1.endswith('.', 5, 10) = False
string1.endswith(' ', 5, 10) = True
string1.endswith('z', 5, 10) = False
string1.endswith('t', 30, 35) = False
expandtabs()
The expandtabs()
method expands the tab sequence in strings to be a custom number of white spaces. Defaults to 8 spaces per tab.
Syntax: expandtabs([tabsize=8])
# Create a test string that contains a single tab (\t) string1 = "\tThis is a test string." print("string1 =", string1) # Set the tab size to 2 whitespaces, using expandtabs(2) string2 = string1.expandtabs(2) print("string2 =", string2) # Test expandtabs() on a string with no tab string3 = "This is a test string." string4 = string3.expandtabs() print("string4 =", string4)
Output:
string1 = This is a test string.
string2 = This is a test string.
string4 = This is a test string.
find()
The find()
method returns the index of the first occurrence of a substring in a string. Returns -1
on failure.
Syntax: find(str[, beg=0][, end=len(string)])
# Create a test string string1 = "This is a test string." print("string1 =", string1) # Use find() to return the first occurrence of 'i' print("string1.find('i') =", string1.find("i")) # Use find() to return first occurence of 'i'. Start index 3 print("string1.find('i', 3) =", string1.find("i", 3)) # Use find() to return first occurrence of 'i'. Start index 6, end index 10 print("string1.find('i', 6, 10) =", string1.find("i", 6, 10))
Output:
string1 = This is a test string.
string1.find('i') = 2
string1.find('i', 3) = 5
string1.find('i', 6, 10) = -1
rfind()
The rfind()
method returns the index of the last occurrence of a substring in a string. Returns -1
on failure.
Syntax: rfind(str[, beg=0][, end=len(string)])
# Create a test string string1 = "This is a test string." print("string1 =", string1) # Use rfind() to return the last occurrence of 'i' print("string1.rfind('i') =", string1.rfind("i")) # Use rfind() to return first occurence of 'i'. Start index 3 print("string1.rfind('i', 3) =", string1.rfind("i", 3)) # Use rfind() to return first occurence of 'i'. Start index -4 print("string1.rfind('i', -4) =", string1.rfind("i", -4)) # Use rfind() to return first occurence of 'i'. Start index 0, end index -6 print("string1.rfind('i', 0, -6) =", string1.rfind("i", 0, -6)) # Use rfind() to return first occurrence of 'i'. Start index 6, end index 10 print("string1.rfind('i', 6, 10) =", string1.rfind("i", 6, 10))
Output:
string1 = This is a test string.
string1.rfind('i') = 18
string1.rfind('i', 3) = 18
string1.rfind('i', -4) = 18
string1.rfind('i', 0, -6) = 5
string1.rfind('i', 6, 10) = -1
index()
Performs a similar function to find()
. Only difference is that it throws ValueError
instead of -1
when substring not found in string.
Syntax: index(str[, beg=0][, end=len(string)])
# Create a test string string1 = "This is a test string." print("string1 =", string1) # Use index() to return the first occurrence of 'i' print("string1.index('i') =", string1.index("i")) # Use index() to return first occurence of 'i'. Start index 3 print("string1.index('i', 3) =", string1.index("i", 3)) # Use index() to return first occurrence of 'i'. Start index 6, end index 10 print("string1.index('i', 6, 10) =", string1.index("i", 6, 10))
Output:
string1 = This is a test string.
string1.index('i') = 2
string1.index('i', 3) = 5
Traceback (most recent call last):
File "", line 11, in
print("string1.index('i', 6, 10) =", string1.index("i", 6, 10))
ValueError: substring not found
rindex()
Performs a similar function to find()
. Only difference is that it throws ValueError
instead of -1
when substring not found in string.
Syntax: rindex(str[, beg=0][, end=len(string)])
# Create a test string string1 = "This is a test string." print("string1 =", string1) # Use rindex() to return the last occurrence of 'i' print("string1.rindex('i') =", string1.rindex("i")) # Use rindex() to return first occurence of 'i'. Start index 3 print("string1.rindex('i', 3) =", string1.rindex("i", 3)) # Use rindex() to return first occurence of 'i'. Start index -4 print("string1.rindex('i', -4) =", string1.rindex("i", -4)) # Use rindex() to return first occurence of 'i'. Start index 0, end index -6 print("string1.rindex('i', 0, -6) =", string1.rindex("i", 0, -6)) # Use rindex() to return first occurrence of 'i'. Start index 6, end index 10 print("string1.rindex('i', 6, 10) =", string1.rindex("i", 6, 10))
Output:
string1 = This is a test string.
string1.index('i') = 2
string1.index('i', 3) = 5
Traceback (most recent call last):
File "", line 11, in
print("string1.index('i', 6, 10) =", string1.index("i", 6, 10))
ValueError: substring not found
isalnum()
The isalnum()
method checks if a string is alphanumeric. Returns Boolean.
# Create a test string string1 = "Test1234" print("string1 =", string1) # Check if string1 isalnum() = True (TRUE) print("string1.isalnum() =", string1.isalnum()) # Include a special character (_) string2 = "Test_1234" print("\nstring2 =", string2) # Check if string2 isalnum() = True (FALSE) print("string2.isalnum() =", string2.isalnum())
Output:
string1 = Test1234
string1.isalnum() = True
string2 = Test_1234
string2.isalnum() = False
isalpha()
The isalpha()
method checks if a string only contains characters [a-z], with no numbers or special characters. Returns Boolean.
Syntax: string.isalpha()
# Create a test string string1 = "Test" print("string1 =", string1) # Check if string1 isalpha() = True (TRUE) print("string1.isalpha() =", string1.isalpha()) # Include a special character (_) string2 = "Test_Special" print("\nstring2 =", string2) # Check if string1 isalpha() = True (FALSE) print("string2.isalpha() =", string2.isalpha()) # Include numbers string3 = "Test1234" print("\nstring3 =", string3) # Check if string2 isalpha() = True (FALSE) print("string3.isalpha() =", string3.isalpha())
Output:
string1 = Test
string1.isalpha() = True
string2 = Test_Special
string2.isalpha() = False
string3 = Test1234
string3.isalpha() = False
isdecimal()
The isdecimal()
method checks whether a string only contains decimal characters. Returns Boolean.
Syntax: string.isdecimal()
# Create a test string string1 = "01456" print("string1 =", string1) # Check if string1 isdecimal() = True (TRUE) print("string1.isdecimal() =", string1.isdecimal()) # Include a decimal point string2 = "014.56" print("\nstring2 =", string2) # Check if string2 isdecimal() = True (FALSE) print("string2.isdecimal() =", string2.isdecimal()) # Include alphabetical characters only string3 = "TestString" print("\nstring3 =", string3) # Check if string3 isdecimal() = True (FALSE) print("string3.isdecimal() =", string3.isdecimal())
Output:
string1 = 01456
string1.isdecimal() = True
string2 = 014.56
string1.isdecimal() = False
string3 = TestString
string3.isdecimal() = False
isdigit()
The isdigit()
method checks whether a string only contains digits. Returns Boolean.
Syntax: string.isdigit()
# Create a test string string1 = "01456" print("string1 =", string1) # Check if string1 isdigit() = True (TRUE) print("string1.isdigit() =", string1.isdigit()) # Include a decimal point string2 = "014.56" print("\nstring2 =", string2) # Check if string2 isdigit() = True (FALSE) print("string2.isdigit() =", string2.isdigit()) # Include alphabetical characters only string3 = "TestString" print("\nstring3 =", string3) # Check if string3 isdigit() = True (FALSE) print("string3.isdigit() =", string3.isdigit()) # Empty string string4 = "" print("\nstring4 = ''") # Check if string4 isdigit() = True (FALSE) print("string4.isdigit() =", string4.isdigit())
Output:
string1 = 01456
string1.isdigit() = True
string2 = 014.56
string1.isdigit() = False
string3 = TestString
string3.isdigit() = False
string4 = ''
string4.isdigit() = False
islower()
The islower()
method checks if all alphabetical characters in a string are lower case. Returns Boolean.
Syntax: string.islower()
# Create a test string string1 = "test string." print("string1 =", string1) # Check if string1 islower() = True (TRUE) print("string1.islower() =", string1.islower()) # Set some characters upper case string2 = "Test String." print("\nstring2 =", string2) # Check if string2 islower() = True (FALSE) print("string1.islower() =", string2.islower()) # Digits only string3 = "123456" print("\nstring3 =", string3) # Check if string3 islower() = True (FALSE) print("string3.islower() =", string3.islower()) # Empty string string4 = "" print("\nstring4 = ''") # Check if string4 islower() = True (FALSE) print("string4.islower() =", string4.islower())
Output:
string1 = test string.
string1.islower() = True
string2 = Test String.
string1.islower() = False
string3 = 123456
string3.islower() = False
string4 = ''
string4.islower() = False
isnumeric()
The isnumeric()
method checks to see if a string only contains numeric characters. Returns Boolean.
Syntax: string.isnumeric()
# Create a test string string1 = "1234567" print("string1 =", string1) # Check if string1 isnumeric() = True (TRUE) print("string1.isnumeric() =", string1.isnumeric()) # Set some characters to be alphabetical string2 = "12345ab" print("\nstring2 =", string2) # Check if string2 isnumeric() = True (FALSE) print("string1.isnumeric() =", string2.isnumeric()) # Numbers with a decimal place string3 = "123.456" print("\nstring3 =", string3) # Check if string3 isnumeric() = True (FALSE) print("string3.isnumeric() =", string3.isnumeric()) # Empty string string4 = "" print("\nstring4 = ''") # Check if string4 isnumeric() = True (FALSE) print("string4.isnumeric() =", string4.isnumeric())
Output:
string1 = 1234567
string1.isnumeric() = True
string2 = 12345ab
string1.isnumeric() = False
string3 = 123.456
string3.isnumeric() = False
string4 = ''
string4.isnumeric() = False
isspace()
The isspace()
method checks to see if a string only contains white space. Returns Boolean.
Syntax: string.isspace()
# Create a test string string1 = " " print("string1 =", "'" + string1 + "'") # Check if string1 isspace() = True (TRUE) print("string1.isspace() =", string1.isspace()) # Set some characters to be alphanumeric string2 = "123 ab" print("\nstring2 =", string2) # Check if string2 isspace() = True (FALSE) print("string1.isspace() =", string2.isspace()) # Empty string string3 = "" print("\nstring3 = ''") # Check if string3 isspace() = True (FALSE) print("string3.isspace() =", string3.isspace())
Output:
string1 = ' '
string1.isspace() = True
string2 = 123 ab
string1.isspace() = False
string3 = ''
string3.isspace() = False
istitle()
The istitle()
method checks to see if all case-based characters that follow non-case based characters are upper case. Returns Boolean.
Syntax: string.istitle()
# Create a test string string1 = "This Is A Title String." print("string1 =", string1) # Check if string1 istitle() = True (TRUE) print("string1.isspace() =", string1.istitle()) # Add some non-case based characters (numbers) string2 = "This Is 4567 Title String." print("\nstring2 =", string2) # Check if string2 istitle() = True (TRUE) print("string2.istitle() =", string2.istitle()) # Set some characters to be numeric string3 = "This is a title string." print("\nstring3 =", string3) # Check if string3 istitle() = True (FALSE) print("string3.istitle() =", string3.istitle()) # Empty string string4 = "" print("\nstring4 = ''") # Check if string4 istitle() = True (FALSE) print("string4.istitle() =", string4.istitle())
Output:
string1 = This Is A Title String.
string1.isspace() = True
string2 = This Is 4567 Title String.
string2.istitle() = True
string3 = This is a title string.
string3.istitle() = False
string4 = ''
string4.istitle() = False
isupper()
The isupper()
method checks if all alphabetical characters in a string are upper case. Returns Boolean.
Syntax: string.isupper()
# Create a test string string1 = "TEST STRING." print("string1 =", string1) # Check if string1 isupper() = True (TRUE) print("string1.isupper() =", string1.isupper()) # Set some characters lower case string2 = "Test String." print("\nstring2 =", string2) # Check if string2 isupper() = True (FALSE) print("string1.isupper() =", string2.isupper()) # Digits only string3 = "123456" print("\nstring3 =", string3) # Check if string3 isupper() = True (FALSE) print("string3.isupper() =", string3.isupper()) # Empty string string4 = "" print("\nstring4 = ''") # Check if string4 isupper() = True (FALSE) print("string4.isupper() =", string4.isupper())
Output:
string1 = TEST STRING.
string1.isupper() = True
string2 = Test String.
string1.isupper() = False
string3 = 123456
string3.isupper() = False
string4 = ''
string4.isupper() = False
ljust()
The ljust()
method will left-justify a string in a given width of characters. If the string it's applied to is shorter than the specified width, a padding character can be specified with fillchar
. Padding will be applied to the right of the string. If no fillchar
value is supplied, space will be used by default.
Syntax: ljust(width[, fillchar])
# Create a test string string1 = "Test" print("string1 =", string1) # Apply ljust(), width shorter than string1 print("string1.ljust(3) =", string1.ljust(3) + "]") # Apply ljust(), width longer than string1, no fillchar print("string1.ljust(6) =", string1.ljust(6) + "]") # Apply ljust(), width longer than string1, 'x' fillchar print("string1.ljust(6, 'x') =", string1.ljust(6, "x"))
Output:
string1 = Test
string1.ljust(3) = Test]
string1.ljust(6) = Test ]
string1.ljust(6, 'x') = Testxx
lower()
The lower()
method converts a string to lower case.
# Create a string string1 = "TeSt StRiNg" print("string1 =", string1) # Apply lower() to string1 print("string1.lower() =", string1.lower())
Output:
string1 = TeSt StRiNg
string1.lower() = test string
lstrip()
The lstrip()
method returns a copy of the string with all leading white space removed by default. You can also specify chars
if you want to remove a string instead, by setting the value within the brackets.
E.g. "eeeReturn".lstrip("e")
would remove all of the 'e' characters from the left of the string, thereby producing "Return".
Syntax: string.lstrip(s[, chars])
print("EXAMPLE 1: lstrip() white space") # Create a string, with white space to the left and right string1 = " Test String " print("string1 =", string1) # Apply lstrip() to string1 string1.lstrip() print("string1.lstrip() =", "[" + string1.lstrip() + "]") print("string1 =", "[" + string1 + "]") # string1 needs to be assigned the result of lstrip() string1 = string1.lstrip() print("\nstring1 after being assigned result of lstrip():") print("string1 =", "[" + string1 + "]") print("\nEXAMPLE 2: lstrip('e')") # Create a string, with a series of leading 'e' characters string1 = "eeeeeTesteeee" print("string1 =", string1) # Assign the result of string1.lstrip('e') back to string1 string1 = string1.lstrip("e") print("\nstring1 after being assigned result of lstrip('e'):") print("string1 =", string1)
Output:
EXAMPLE 1: lstrip() white space
string1 = Test String
string1.lstrip() = [Test String ]
string1 = [ Test String ]
string1 after being assigned result of lstrip():
string1 = [Test String ]
EXAMPLE 2: lstrip('e')
string1 = eeeeeTesteeee
string1 after being assigned result of lstrip('e'):
string1 = Testeeee
maketrans()
The maketrans()
method creates a translation table, mapping old values to new values. This is then used for character replacement in the translate()
method.
- 1 argument (x): Must be a dictionary, where each key is a single character or unicode number
- 2 arguments (x and y): Two strings of equal length
- 3 arguments (x, y and z): Same as for 2 arguments, but with the third argument mapped to None
Syntax: string.maketrans(x[, y[, z]])
# Create a test string string1 = "This is a test string." print("string1 =", string1) # Use maketrans(dict) to create a translation table to unicode print("\nEXAMPLE 1: maketrans() with 1 argument") dict1 = {"a":"A", "h":"H", "g":"great"} print("dict1 =", dict1) print("string1.maketrans(dict1) =\n", string1.maketrans(dict1)) # Use maketrans(string, string) to create a translation table (dictionary) print("\nEXAMPLE 2: maketrans() with 2 arguments") trans1 = "aeiou" trans2 = "abcde" print(("trans1 = {0}. trans2 = {1}").format(trans1, trans2)) print("string1.maketrans(trans1, trans2) =\n", string1.maketrans(trans1, trans2))
Output:
string1 = This is a test string.
EXAMPLE 1: maketrans() with 1 argument
dict1 = {'a': 'A', 'h': 'H', 'g': 'great'}
string1.maketrans(dict1) =
{97: 'A', 104: 'H', 103: 'great'}
EXAMPLE 2: maketrans() with 2 arguments
trans1 = aeiou, trans2 = abcde
string1.maketrans(trans1, trans2) =
{97: 97, 101: 98, 105: 99, 111: 100, 117: 101}
replace()
The replace()
method will return a copy of the string where the old
string has been replaced with the new
string. Case sensitive.
The number of times to apply this replacement can be limited by passing a value to the max
parameter.
Syntax: replace(old, new[, max])
# Create a test string string1 = "This is a test string." print("string1 =", string1) # Use replace() to substitute 's' for 'n' print("\nEXAMPLE 1: Replace 's' with 'n'") string2 = string1.replace("s", "n") print("string1.replace('s', 'n') =", string2) # Use replace() to substitute 't' for 'a' to check case sensitivity print("\nEXAMPLE 2: Check case sensitivity with 't'") string3 = string1.replace("t", "a") print("string1.replace('t', 'a') =", string3) # Use replace() to substitute 's' for 'n', a maximum of 2 times print("\nEXAMPLE 3: Replace 's' a maximum of 2 times") string4 = string1.replace("s", "n", 2) print("string1.replace('s', 'n', 2) =", string4) # Attempt to replace() a character that doesn't appear in the string print("\nEXAMPLE 4: Attempt to replace 'x' with 'n'") string5 = string1.replace("x", "n") print("string1.replace('x', 'n') =", string5)
Output:
string1 = This is a test string.
EXAMPLE 1: Replace 's' with 'n'
string1.replace('s', 'n') = Thin in a tent ntring.
EXAMPLE 2: Check case sensitivity with 't'
string1.replace('t', 'a') = This is a aesa saring.
EXAMPLE 3: Replace 's' a maximum of 2 times
string1.replace('s', 'n', 2) = Thin in a test string.
EXAMPLE 4: Attempt to replace 'x' with 'n'
string1.replace('x', 'n') = This is a test string.
rjust()
The rjust()
method will right-justify a string in a given width of characters. If the string it's applied to is shorter than the specified width, a padding character can be specified with fillchar
. Padding will be applied to the left of the string. If no fillchar
value is supplied, space will be used by default.
Syntax: rjust(width[, fillchar])
# Create a test string string1 = "Test" print("string1 =", string1) # Apply rjust(), width shorter than string1 print("string1.rjust(3) =", "[" + string1.rjust(3)) # Apply rjust(), width longer than string1, no fillchar print("string1.rjust(6) =", "[" + string1.rjust(6)) # Apply rjust(), width longer than string1, 'x' fillchar print("string1.rjust(6, 'x') =", string1.rjust(6, "x"))
Output:
string1 = Test
string1.rjust(3) = [Test
string1.rjust(6) = [ Test
string1.rjust(6, 'x') = xxTest
rstrip()
The rstrip()
method returns a copy of the string with all trailing white space removed by default. You can also specify chars
if you want to remove a string instead, by setting the value within the brackets.
E.g. "Returneee".rstrip("e")
would remove all of the 'e' characters from the right of the string, thereby producing "Return".
Syntax: rstrip(s[, chars])
print("EXAMPLE 1: rstrip() white space") # Create a string, with white space to the left and right string1 = " Test String " print("string1 =", string1) # Apply rstrip() to string1 string1.rstrip() print("string1.rstrip() =", "[" + string1.rstrip() + "]") print("string1 =", "[" + string1 + "]") # string1 needs to be assigned the result of rstrip() string1 = string1.rstrip() print("\nstring1 after being assigned result of rstrip():") print("string1 =", "[" + string1 + "]") print("\nEXAMPLE 2: rstrip('e')") # Create a string, with a series of leading 'e' characters string1 = "eeeeeTesteeee" print("string1 =", string1) # Assign the result of string1.rstrip('e') back to string1 string1 = string1.rstrip("e") print("\nstring1 after being assigned result of rstrip('e'):") print("string1 =", string1)
Output:
EXAMPLE 1: rstrip() white space
string1 = Test String
string1.rstrip() = [ Test String]
string1 = [ Test String ]
string1 after being assigned result of rstrip():
string1 = [ Test String]
EXAMPLE 2: rstrip('e')
string1 = eeeeeTesteeee
string1 after being assigned result of rstrip('e'):
string1 = eeeeeTest
split()
The split()
method splits a string into sections based on a specified string. These sections are returned in the form of a list. If no value is specified for the str
parameter, whitespace is used by default.
Syntax: split([str=""][, num=string.count(str)])
# Create a test string string1 = "This is a test string." print("string1 =", string1) # Use split() with its default (split on white space) list1 = string1.split() print("string1.split() =", list1) # Use split() with its default (split on white space). Max. 2 splits. list1 = string1.split(' ', 2) print("string1.split(' ', 2) =", list1) # Apply split('s') to string1 list2 = string1.split('s') print("\nstring1.split('s') =", list2) # Apply split('s') to string1. Max. 2 splits. list2 = string1.split('s', 2) print("string1.split('s', 2) =", list2)
Output:
string1 = This is a test string.
string1.split() = ['This', 'is', 'a', 'test', 'string.']
string1.split(' ', 2) = ['This', 'is', 'a test string.']
string1.split('s') = ['Thi', ' i', ' a te', 't ', 'tring.']
string1.split('s', 2) = ['Thi', ' i', ' a test string.']
startswith()
The startswith()
method can be used to check if a string starts with a specific character. Case sensitive. Returns Boolean.
Syntax: startswith(prefix[, beg=0][, end=len(string)])
# Create a test string string1 = "This is a test string." print("string1 =", string1) # Check if string1 startswith('T') print("string1.startswith('T') =", string1.startswith("T")) # Check if string1 startswith('t') print("string1.startswith('t') =", string1.startswith("t")) # Check if string1 startswith('z') print("string1.startswith('z') =", string1.startswith("z")) # Check if string1 startswith('i'). Start index = 5 print("string1.startswith('i', 5) =", string1.startswith("i", 5)) # Check if string1 startswith('i'). Start index = 0, end index = 2 print("string1.startswith('i', 0, 2) =", string1.startswith("i", 0, 2)) # Check if string1 startswith(' '). Start index = 0, end index = 2 print("string1.startswith(' ', 0, 2) =", string1.startswith(" ", 0, 2)) # When a str value is passed in that doesn't exist in the string print("string1.startswith('z', 5, 10) =", string1.startswith("z", 5, 10)) # When a start index is passed in that's too large print("string1.startswith('t', 30, 35) =", string1.startswith("t", 30, 35))
Output:
string1 = This is a test string.
string1.startswith('T') = True
string1.startswith('t') = False
string1.startswith('z') = False
string1.startswith('i', 5) = True
string1.startswith('i', 0, 2) = False
string1.startswith(' ', 0, 2) = False
string1.startswith('z', 5, 10) = False
string1.startswith('t', 30, 35) = False
strip()
The strip()
method returns a copy of the string with all leading and trailing white space removed by default. You can also specify chars
if you want to remove a string instead, by setting the value within the brackets.
E.g. "eeeReturneee".strip("e")
would remove all of the 'e' characters from the left of the string, thereby producing "Return".
Syntax: string.strip(s[, chars])
print("EXAMPLE 1: strip() white space") # Create a string, with white space to the left and right string1 = " Test String " print("string1 =", string1) # Apply strip() to string1 string1.strip() print("string1.strip() =", "[" + string1.strip() + "]") print("string1 =", "[" + string1 + "]") # string1 needs to be assigned the result of strip() string1 = string1.strip() print("\nstring1 after being assigned result of strip():") print("string1 =", "[" + string1 + "]") print("\nEXAMPLE 2: strip('e')") # Create a string, with a series of leading and trailing 'e' characters string1 = "eeeeeTesteeee" print("string1 =", string1) # Assign the result of string1.strip('e') back to string1 string1 = string1.strip("e") print("\nstring1 after being assigned result of strip('e'):") print("string1 =", string1)
Output:
EXAMPLE 1: strip() white space
string1 = Test String
string1.strip() = [Test String]
string1 = [ Test String ]
string1 after being assigned result of strip():
string1 = [Test String]
EXAMPLE 2: strip('e')
string1 = eeeeeTesteeee
string1 after being assigned result of strip('e'):
string1 = Test
swapcase()
The swapcase()
reverses the casing of all case-based characters. Returns a copy of the string.
Syntax: string.swapcase()
# Create a mixed-case string string1 = "TeSt StRiNg" print("string1 =", string1) # Apply swapcase() to string1 print("string1.swapcase() =", string1.swapcase()) # Create a string that's entirely lower case string2 = "test string" print("\nstring2 =", string2) # Apply swapcase() to string2 print("string2.swapcase() =", string2.swapcase()) # Create a string that's entirely upper case string3 = "TEST STRING" print("\nstring3 =", string3) # Apply swapcase() to string3 print("string3.swapcase() =", string3.swapcase()) # Create a string that's entirely numeric string4 = "1234567" print("\nstring4 =", string4) # Apply swapcase() to string4 print("string4.swapcase() =", string4.swapcase())
Output:
string1 = TeSt StRiNg
string1.swapcase() = tEsT sTrInG
string2 = test string
string2.swapcase() = TEST STRING
string3 = TEST STRING
string3.swapcase() = test string
string4 = 1234567
string4.swapcase() = 1234567
upper()
The upper()
method converts a string to upper case.
Syntax: string.upper()
# Create a string string1 = "TeSt StRiNg" print("string1 =", string1) # Apply upper() to string1 print("string1.upper() =", string1.upper())
Output:
string1 = TeSt StRiNg
string1.upper() = TEST STRING