• Top Members
  • 834 Replies
    2585 Replies
  • 716 Replies
    2026 Replies
  • 331 Replies
    1928 Replies

Python Basics: Strings

User avatar
Coding God
Posts: 1242

Python Basics: Strings

Tue Mar 18, 2014 10:40 pm

As there aren't many tutorials in the Python section, I thought it would be time something got posted to it lol. And what better time than Mad March to start a new tutorials series!

I'm calling it "Python Basics", and as the title suggests, it will go over some simple concepts in Python. The first few tutorials will focus on data types, then we'll move on to conditionnals, functions, and perhaps eventually object-oriented programming.

Let's get started, shall we?

Strings in Python

Python strings, like strings in most programming languages, are fairly simple to grasp. They can contain one or more characters (Unicode or otherwise) and simple operations may be performed on them. However, the main difference between Strings in Python and Strings in most languages is the concept of mutability.

In Python, Strings are considered to be immutable. Simply put, that means they cannot be changed once created. The following code example will easily demonstrate this concept (it is widely used to explain Python data type mutability):

Code: Select all

a = 10

def increment(n):
>>>>n = n + 1

One might think the result would be 11. After all, we set the variable "a" to 10, then passed it to a function whose purpose is to increment the variable by 1. In reality, Python will print out "10", because the variable hasn't been changed. This is immutability. Of course, here it is shown using Numbers, but the same goes with Strings.

That said, the only way to change an immutable variable in Python is to change its object reference:

Code: Select all

a = 10
a = a + 1

Here Python will print out "11", because variable a has been reassigned to a new Number object with a value of 11.

Creating Strings
Now that we've gone over what Strings actually were, let's look at how we create them. As expected, creating Strings is pretty straightforward:

Code: Select all

a = "your text"
b = 'Your text'
d = """Your very long text
       That may span over more than one line"""
d = str(70)
There are three main ways of creating Strings: the first three are simply wrapping text with quotes (either single, double, or triple for multiline strings). The third method is by using the value returned by the str function. This simply converts whatever data type passed as an argument to a String.

Strings may also be concatenated, or stuck together, with the "+" operator:

Code: Select all

a = "This is"
b = " a very nice String"

c = a + b


Result: "This is a very nice String"
When inserting special characters in a Python String (such as quotation marks), you must escape them in order for Python to interpret them correctly. This is done with the "\" backslash:

Code: Select all

a = "The quick brown fox exclaimed \"Get out of the way!\" as he jumped over the lazy dog"
b = "I like inserting random backslashes into my strings \\"


Result a: "The quick brown fox exclaimed "Get out of the way!" as he jumped over the lazy dog"
Result b: "I like inserting random backslashes into my strings \"
String comparisons

Like most data types in Python, Strings can be compared. Of course you can use the usual "==" equals or "!=" does not equal comparators, but Python Strings also support the "<" less than, ">" greater than, "<=" less than or equal to and ">=" greater than or equal to comparators. In the case of <, >, <= or >=, Strings are compared using their character codes. (in ASCII, for example, lowercase a is 97, while lowercase b is 98).

String slicing
Strings in Python can be sliced, kind of like how VB.NET supports SubStrings. Slicing in Python, however, is applicable to all objects that are sequences. Sequences include Strings, Lists and Tuples, but we'll see those later on :). The syntax for String (or sequence) slicing in Python is quite simple:

Code: Select all

a = "a string"

b = a[2] #b will be equal to "string"
c = a[2:4] #c will be equal to "st"
d = a[2:6:2] #d will be equal to "sr"

e = a[-3] #e will be equal to "ing"
Simply put, three syntaxes are available:

Code: Select all

The last syntax option lets you skip over characters if you wish.

To better understand slicing, think of it as like slicing a loaf of bread. Your bread, in this case, is a String:

"a string"

Now let's slice it up into individual characters

"|a| |s|t|r|i|n|g"

Each "|" delimiter is a "slice" of our String. So if we wanted the first three characters ("a s"), we would set the start slice at 0, and the end slice at 3:

"|a| |s|"

A slice is made at index 3 (just before the 4th character), but the fourth character isn't included in the slice... just like real bread :D

More String functions

Many more String functions are available in Python, such as lower() and upper() to convert the String to lowercase or uppercase respectively, but I won't cover them all in this tutorial. I suggest you check out the official Python documentation and the section on String operations for more information: Python String documentation

I hope you enjoyed this tutorial, the first of what I hope will be a nice series, and as always, go crazy! cooll;

Post Reply

Return to “Tutorials”