Introduction To Strings In Python

Introduction

In this article, we'll directly get our hands dirty with Python strings. 

If you want to learn Python strings fast and focus on the practical concepts and built-in methods/functions, you have come to the right place.

OK, let's get started then.

What is a String in Python?

In Python, strings are easy to understand at first glance, but you'll see them in different ways of usage when you have deepened your knowledge and experience in Python.

Just remember that in Python, a string is a series of characters, and these characters are inside quotes.

These quotes can use single or double around your lines.

Let's see an example below.

#let's define a variable named my_name and assign a value of Jin Vincent Necesario.
my_name = "Jin Vincent Necesario"
print(my_name)

#let's define another variable, and assign this value 'C# Corner Rocks'.
message = 'C# Corner Rocks'
print(message)

This will output the following:

python_string_example

Getting the Length of Characters in a String

This section will show how to get the number of characters in a string.

Honestly, this is easy. Just use the built-in method len().

Let's see an example below.

# output 15
print(len("C# Corner Rocks"))
# output 6
print(len("Python"))

Using Variables Inside a String

In most programming languages, especially Python, you can't ignore that sometimes you need to use a variable's value inside a string.

To instantly insert a variable's value into a string, place the letter f immediately before the opening quotation mark.

Then you can put braces around the name or names of any variable you want to use inside the string.

Let's see an example.

# Let's define 2 variables (first_name & last_name) and assign values.
# Then put them inside a variable (full_name).
first_name = "Jin"
last_name = "Necesario"
full_name = f"{first_name} {last_name}"
print(full_name)

This will output the following:

python_strings_f_strings

Within the code sample, the full_name variable assigned to it is called f-strings.

The f stands for the format. It formats the string by replacing the name of any variable in braces with its value.

Note: The f-strings were introduced in Python 3.6, so you'll need to use the format() method earlier version of Python.

Let's have more examples, f-strings with its counterpart format() method.

# Variables that will be used by f-strings and format() method
community_name = "C# Corner"
programming_language = "Python"
first_name = "Jin"
age = "100"

print("Start of f-strings examples")
# Let's explore f-strings
first_msg = f"{first_name.upper()} wants to live until {age}."
print(first_msg)

second_msg = f"I love {community_name}."
print(second_msg)

third_msg = f"I love C# & JS & I also love {programming_language}."
print(third_msg)
print("End of f-strings examples")

print("")

print("Start of format() method examples")
# Let's explore format() method
first_msg = "{0} wants to live until {1}.".format(first_name.upper(), age)
print(first_msg)

second_msg = "I love {0}.".format(community_name)
print(second_msg)

third_msg = "I love C# & JS & I also love {0}.".format(programming_language)
print(third_msg)
print("End of format() method examples")

This will output the following:

python_fstrings_and_format_method

Python Escape Characters

There are nonprinting characters in programming, such as tabs, spaces, and end-of-line symbols.

These characters can help you format or organize your strings output, which is more straightforward for you or your users to read.

Why are escape characters essential for us to understand? If you agree, there are times you'll experience syntax errors (Python doesn't recognize a section of your program as a valid Python code).

Moreover, the most common syntax error is using an apostrophe within a single quote string or using a double-quote within a double-quoted string.

That's why knowing and understanding these escape characters are essential for you to learn Python strings.

Character Description
\n Newline
\t Horizontal Tab
\r Carriage return
\b Backspace
\' Single quote
\" Double quote
\\ Backslash
\v Vertical tab

Let's see some examples below and let yourself explore the others.

Working with a newline

# new lines

print("Here are the languages that I currently work with:\n*Python\n*C#\n*JavaScript\n*and Visual Basic.")

This will output the following: 

python_new_line_strings

Working with horizontal tab

# tabs

print("\tPL\tAPI")
print("\t------\t-----")
print("\tPython\tFlask")
print("\tC#\tWebApi")
print("\tJS\tNode.js")

This will output the following: 

Working with Single Quotes

# let's try to show single quote inside a single quote string
print('Words with apostrophes')
print('he\'s = he is')
print('I\'d = I had')
print('I\'m = I am')

This will output the following: 

python_strings_escape_character_single_quote

Working with Double Quotes

# let's try to show sentences starting & ending with double quotes inside a double-quoted string

print("\"While there's code there's bug\"")
print("\"Don't comment bad code - rewrite it.\"")

This will output the following: 

python_strings_double_quotes_escape_character

Python String Methods

A couple of built-in methods will get you started with Python strings.

Remember that these built-in methods are used on strings and return a new value. Thus these methods don't change the original string.

By the way, we won't be tackling every technique. We'll choose those essential methods for you to get started.

Just in case you're wondering what would happen if we invoked the string method with a different type, let's say a number five, then dot, then invoke the method upper (5.upper()), you'll have an exception.

Changing Python String Case

The upper & lower Methods

The upper method - converts the whole string into its upper-case equivalent.

Let's see an example.

first_string = "Python"
# convert Python to PYTHON
print(f"{first_string.upper()}")

The lower method - converts the whole string into its lower-case equivalent. 

Let's see an example.

second_string = "PYTHON"
# convert PYTHON to python
print(f"{second_string.lower()}")

The title & capitalize Methods

The capitalize method - converts the first character to upper-case and makes remaining characters in the string lower-case, while the title method - converts the first character of each word to upper-case and the remaining characters to lower-case.

Let's see an example.

third_string = "mR. nEcesario"

# only capitalize the first character and the rest to lower-case
# converts mR. necesario to Mr. necesario
print(f"{third_string.capitalize()}")

# capitalizes the first character of each word and the rest to lower-case
# output Mr. Necesario
print(f"{third_string.title()}")

Checking Python Strings If Starts or Ends With a Character

Sometimes as a developer, we would like to check if a specific string starts or ends with a particular character or characters.

The startswith method – returns true if the string begins with the value you passed, while the endswith method – returns true if the string ends with the value you provided.

Let's see some examples.

#startswith and endswith

mutant_1 = "wolverine"
print(f'{mutant_1.startswith("w")}')  # True
print(f'{mutant_1.startswith("W")}')  # False

print("")

mutant_3 = "Gambit"
print(f'{mutant_3.startswith("Ga")}')  # True
print(f'{mutant_3.startswith("Gam")}')  # True

print("")

mutant_2 = "storm"
print(f'{mutant_2.endswith("m")}')  # True
print(f'{mutant_2.endswith("M")}')  # False

print("")

mutant_4 = "Jubilee"
print(f'{mutant_4.endswith("lee")}')  # True
print(f'{mutant_4.endswith("e")}')  # True

Trimming Python Strings

Extra whitespace in a given string is confusing, especially to beginners.

'C# Corner' and 'C# Corner ' look the same. But when this is run and read by the Python interpreter, they're two different things unless you specify by invoking a method that strips whitespaces.

Which is also applies to other programming languages.

Let's see an example.

print(('C# Corner ' == 'C# Corner')) # False
print(('C# Corner' == 'C# Corner'))  # True

Hopefully, this time you see the point.

OK, let's try to see methods specific for trimming whitespaces.

These are strip, lstrip, and rstrip.

Let's see some examples again before we explain these methods.

compareto = "C# Corner Rocks"

print(('  C# Corner Rocks  '.strip() == compareto))  #True
print((' C# Corner Rocks').lstrip() == compareto)  # True
print(('C# Corner Rocks '.rstrip() == compareto))  # True

In the examples above, we can say that the strip method removes spaces both at the beginning and end of the string.

The lstrip, on the other hand, actually removes whitespaces at the beginning/left of the string, while rstrip removes the whitespaces at the end/right of the string.

Summary

In this article, we have discussed the following,

  • What is a String In Python?
    • Getting the Length of Characters in a String
  • Using Variables Inside a String
  • Python Escape Characters
    • Working with a newline
    • Working with horizontal tab
    • Working with Single Quotes
    • Working with Double Quotes
  • Python String Methods
    • Changing Python String Case
    • Checking Python String If Starts or Ends With a Character
    • Trimming Python Strings

I hope you have enjoyed this article.

Once again, I hope you have enjoyed this article/tutorial as I have enjoyed writing it.

Stay tuned for more. Until next time, happy programming!

Please don't forget to bookmark, like, and comment.

Cheers! and Thank you!


Similar Articles