Xtralien Scientific Python: Strings


Strings are ubiquitous in programming. They can be very useful in explaining what is happening at any given point in a program. At their core a string is simply a series of characters. Often text strings will contain regular words and sentences, however they are not required too.

string_a = "Hello world!"
string_b = "Hlelo wrold!"

In the example above both string_a and string_b are strings although string_b does not contain a correct english sentence.

Creating a string

As seen above, strings can be created by using quotes. In Python both single ' and double " quotes can be used to create strings. The quotes must appear at the beginning and end of the string and must match.

For example, the following are two valid examples of the same string. As you can see, the quotes are the same at the beginning and end of each of the strings.

single_quote = 'Hello World!'
double_quote = "Hello World!"

Once created a string cannot be modified. In this way they are like tuples.

Strings are very useful for communicating with scientific instruments, such as with the Xtralien X100.

It is possible to create new strings by adding strings together. This will result in a new string.

new_string = 'Hello' + ' ' + 'World!' 

The example above will result in the string 'Hello World!' being assigned to variable new_string.

Accessing a string

Usually a string is accessed all at once, either to compare or to print. However, like a tuple you can access slices of strings. This is done in the same way as tuple and lists.

hello = single_quote[:5]

This would assign the value 'Hello' to the variable hello.

Transforming to strings

Most types of value in Python can be transformed into strings using the builtin str function.

string_1 = str(1)

The example above assign the value '1' to the variable string_1.

Formatting strings

String formatting is useful when preparing to print values. In other languages, such as C, you prepare string using %-formatting. You can also format like this in Python, like below.

formatted_string = 'Hello %s' % 'World'

This will assign the value 'Hello World' to the variable formatted_string. This is because 'World' is inserted in place of %s.

With new versions of Python, the string type has gained a format method, which can be used for easier formatting. When using this method the %-formats are replaced with {} and the str version of each type is used instead.

The example above could be rewritten using the format method as below.

formatted_string = 'Hello {}'.format('World')

This would provide the same result as the first example and it is more pythonic because it doesn’t rely on any types.