Working with Strings in Python

Working with Strings in Python

Requirements:

  • Python programming Interpreter - You can download python for windows, macOS, and Ubuntu for free at Python Official Website. ensure you download version of python 3 (maybe 3.8.0). all the code in this blog post were written to run on python 3.
  • Python IDE (Integrated Development Environment) such as Mu, PyCharm or Vs Code. Download Mu from Mu Official Website and Pycharm from Jetbrains

Note: You can write the codes and run it online through Python Online Compiler

In this blog post, we’ll look at the way Python let you write, print and access strings in your code.

String Literals

Typing string values in Python code is fairly straightforward: they begin and end with either a single quote or double quote.

print ('Hello World!')
print ("Hello World!")
>>>

But then how can you use a quote inside a string? For instance 'That is my dad’s car.'

Single quote at the beginning and end of the string won’t work here, because Python will think the string ends after dad, and the rest (s car.') is invalid Python code. Fortunately, this is where double quote usage comes handy.

print ("That is my dad’s car")

That is my dad's car
>>>

Escape Character

An escape character lets you use characters that are otherwise impossible to put into a string. Backlash () is use to escape such character. Backlash comes first follow by the character to be escaped. In the example given above. You can choose to use backlash () to escape the (‘) as shown below instead of using the double quote option.

print ('This is my dad\'s car')

dadscar.JPG Python is intelligent to know that since the single quote in dad\'s has a backslash, it is not a single quote meant to end the string value. The escape characters \' and \" let you put single quotes and double quotes inside your strings, respectively.

List of Escape characters and what they do;

Capture1.JPG Enter the following into the interactive shell:

print ('Hey there!\n How are you doing?\n I\'m Stephen by name\n It\'s nice meeting you.')

hey.JPG

Raw String

In a case where you want both the \ and escape character to be displayed in your output, you covert the string value into a raw string by placing r before the beginning of the quotation mark of a string. A raw string completely ignore all escape character and print the backlash that appears in the string.

For example, enter the following into the interactive shell:

print (r'That is Atiku\'s cap.')

raw.JPG

Multiline Strings with Triple Quotes

While you can use the \n escape character to put a newline into a string, it is often easier to use multiline strings. A multiline string in Python begins and ends with either three single quotes or three double quotes. Any quotes, tabs, or newlines in between the “triple quotes” are considered part of the string. Python’s indentation rules for blocks do not apply to lines inside a multiline string.

Enter the following into the interactive shell;

print('''Dear Stev, 
Ugochi's cat has been arrested for catnapping, cat burglary, and extortion. 
Sincerely, 
Stev''')

dearstev.JPG

Multiline Comments

While the hash character (#) marks the beginning of a comment for the rest of the line, a multiline string is often used for comments that span multiple lines. The following is perfectly valid Python code:

"""This is a test Python program. This program was designed for Python 3, not Python 2. """
print('Hello!')
or
'''This is a test Python program. This program was designed for Python 3, not Python 2.'''
print('Hello!')

hello.JPG When the code above was run, only the print('Hello!') command line was executed while the lines above it was commented out not to be interpreted by python by using ''' or """ at the beginning and end it.

Indexing and Slicing Strings

Strings use indexes and slices the same way lists do. You can think of the string 'Hello, world!' as a list and each character in the string as an item with a corresponding index.

index1.JPG The space and exclamation point are included in the character count, so 'Hello, world!' is 13 characters long, from H at index 0 to ! at index 12.

To perform Indexing operation on string, enter the following into the interactive shell:

A1 = 'Hello, world!'
print = (A1[0])

h.JPG

A1 = 'Hello, world!'
print (A1[0:5])

he.JPG If you specify an index, you’ll get the character at that position in the string. If you specify a range from one index to another, the starting index is included and the ending index is not. That’s why, if A1 is 'Hello, world!', A1[0:5] is 'Hello'. The substring you get from A1[0:5] will include everything from A1[0] to A1[4], leaving out the comma at index 5 and the space at index 6. This is similar to how range(5) will cause a for loop to iterate up to, but not including, 5.

The in and not in Operators with Strings

An expression with two strings joined using ‘in or not in’ will evaluate to check whether the first string (the exact string, case sensitive) can be found within the second string. The expression returns a Boolean True or False to indicate if it’s found or not.

Enter the following into the interactive shell:

print('Hello' in 'Hello, World')

t.JPG Check this out too:

print('HELLO' in 'Hello, World')

f.JPG Also:

print('cats' not in 'cats and dogs')

f.JPG

Putting Strings inside Other Strings

Putting strings inside other strings is a common operation in programming. One way this can be achieved in python is by using + operator.

name = 'Sani Nicolas' 
age = 40 
print ('Hello, my name is ' + name + '. I am ' + str(age) + ' years old.' )

sani.JPG Puting strings inside other strings using + is also called concatenation

String replication

The operator multiplies two integer or floating-point value. but when is used on one string value and one integer value, it becomes the string replication operator

print ('Ajoke' * 5 )

a.JPG

References

Thanks for reading this article. If you like these blog post, please share it with your friends and colleagues. If you have any questions or feedback, please drop a note.

Best regards!