Strings in Python: Your Pathway to Text Manipulation Mastery - w9school

Python strings are sequences of characters, versatile and essential data types for text processing. They support manipulation and formatting with ease.

Strings in Python: Your Pathway to Text Manipulation Mastery - w9school

Python Strings

Strings

Python uses either single quotation marks or double quotation marks for defining strings.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example

print("Hello")
print('Hello')

Now Try it Yourself.>>

Assign String to a Variable

The variable name, an equal sign, and the string are used to assign a string to the variable: 

Example

a = "Hello"
print(a)

Multiline Strings

A multiline string can be assigned to a variable by enclosing it in three quotes:

Example

You may use three double quotation marks:

a = """I'm a Python String"""
print(a)

Or three single quotes:

Example

a = '''I am a string too'''
print(a)

Note: Please take note that the line breaks in the result are placed exactly where they are in the code.

Strings are Arrays

Python's strings, like those of many other widely used programming languages, are collections of bytes that represent unicode characters.

Python does not, however, support character data types; instead, a single character is represented as a string with length 1.

To access the string's constituents, use square brackets.

Example

Get the character in position 1 (remember, the first character is in position 0):

a = "Hello, World!"
print(a[1])

Looping Through a String

Since strings are arrays, we can loop through the characters in a string, with a for loop.

Example

Loop through the letters of the word "banana":

for x in "banana":
  print(x)

String Length

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))

Check String

To check if a certain phrase or character is present in a string, we can use the keyword in.

Example

Verify the word "free" appears in the following text:

txt = "The best things in life are free!"
print("free" in txt)

Use it in an if statement:

Example

Only print if "free" is present:

txt = "The best things in life are free!"
if "free" in txt:
  print("Yes, 'free' is present.")

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

Verify that the following text DOES NOT contain the word "expensive":

txt = "The best things in life are free!"
print("expensive" not in txt)
Use it in an if statement:

Example

only print if "expensive" is not present:

txt = "The best things in life are free!"
if "expensive" not in txt:
  print("No, 'expensive' is NOT present.")

Slicing

The slice syntax allows you to return a range of characters.

To return a portion of the string, enter the start index and the end index, separated by a colon.

Example

The characters from positions 2 to 5 (not included) should be obtained:

b = "Hello, World!"
print(b[2:5])

Now Try it Yourself.>>

Note: The first character has index 0.

Slice From the Start

If the start index is omitted, the range's beginning character is the first one:

Example

Get the characters (not included) from position 1 to position 5:

b = "Hello, World!"
print(b[:5])

Now Try it Yourself.>>

Slice To the End

The range will extend to the end if the end index is omitted:

Example

Get the characters starting at position 2 and continuing to the very end:

b = "Hello, World!"
print(b[2:])

Negative Indexing

Start the slice from the end of the string using negative indexes:

Example

Obtain the characters:

"World!" (position -5) from: "o"

To, but not including: "d" in "World!" (position -2):

b = "Hello, World!"
print(b[-5:-2])

Python - Modify Strings

There are several built-in methods in Python that you may apply to strings.

Upper Case

Example

The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper())​

Now Try it Yourself.>>

Lower Case

Example

The lower() method returns the string in lower case:

a = "Hello, World!"
print(a.lower())

Remove Whitespace

Whitespace is the space before and/or after the actual text, and very often you want to remove this space.

Example

The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

Replace String

Example

The replace() method replaces a string with another string:

a = "Hello, World!"
print(a.replace("H", "J"))

Split String

The split() method returns a list where the text between the specified separator becomes the list items.

Example

The split() method splits the string into substrings if it finds instances of the separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

String Concatenation

Use the + operator to concatenate, or merge, two strings.

Example

Merge variable a with variable b into variable c:

a = "Hello"
b = "World"
c = a + b
print(c)

Now Try it Yourself.>>

Example

Add a " " to create a space between them.

a = "Hello"
b = "World"
c = a + " " + b
print(c)

String Format

We learned that combining strings and numbers in this way is not possible in the Python Variables chapter.

Example

age = 36
txt = "My name is John, I am " + age
print(txt)​

Now Try it Yourself.>>

But by utilizing the format() technique, we can combine texts and numbers!

The given arguments are formatted using the format() method, which also inserts them into the string in the appropriate placeholders:

Example

Use the format() method to insert numbers into strings:

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

Now Try it Yourself.>>

The format() method accepts an infinite number of arguments, which are added to the appropriate placeholders as follows:

Example

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))​

Now Try it Yourself.>>

You can use index numbers {0} to be sure the arguments are placed in the correct placeholders:

Example

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))​

Now Try it Yourself.>>

Escape Character

Use an escape character to inserted prohibited characters into a string.

Backslashes and the character you want to insert are considered escape characters.

A double quotation within a string that is encircled by double quotes is an illustration of an unlawful character:

Example

If you use double quotes within a string that is enclosed in double quotes, you will receive the following error:

txt = "We are the so-called "Vikings" from the north."

Now Try it Yourself.>>

The escape character "\" should be used to resolve this issue:

Example

When using double quotes, you are permitted to do so when using the escape character:

txt = "We are the so-called \"Vikings\" from the north."

Now Try it Yourself.>>

Escape Characters

Python also uses the following escape symbols:

Code Result
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value

Now Try it Yourself.>>

String Methods

You can use a variety of built-in methods on strings in Python.

Note: Every string method produces fresh values. The original string is left unchanged.

Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns how many times a given value appears in a string.
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Returns the location of the value discovered after searching the string for a given value.
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Returns the location where a certain value was located after searching the string for it.
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if the string only contains alphabetic characters.
isascii() Returns True if all of the characters in the string are ascii characters.
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if the string only contains lowercase letters.
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string complies with a title's criteria.
isupper() Returns True if the string contains just uppercase characters.
join() Connects an iterable's elements to the string's end.
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple that is separated into the three parts of the string.
replace() Returns a string where a specified value is replaced with a specified value
rfind() Returns the last location where a particular value was discovered after searching the string for it.
rindex() Returns the latest location where the value was located after searching the string for the given value.
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a string with the proper trim.
split() Returns a list after splitting the string at the designated separator.
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning

Test Yourself With Exercises

Now you have learned a lot about Strings, and how to use them in Python.

Are you ready for a test?

If yes Then Click Here for your Python String Test.

What's Your Reaction?

like

dislike

love

funny

angry

sad

wow