Python Scripting For Linux System Administrators — Strings
System Administrators in general are not Developers and lacks in Programming skills. This is an attempt from myside to document the basic concepts of Python to make their Life Easier while learning this amazing scripting language.
For Python series my articles will be short and crisp. There won’t be any lengthy explanations.
In this series we will go through the necessary features of the Python language to be able to leverage its additional benefits in writing scripts and creating command line tools (data types, loops, conditionals, functions, error handling, and more).
Please go through this article for installation of Python 3 on RHEL/CentOS systems.
Lets start understanding the concepts now.
Strings
A string is a sequence of characters grouped together.
String literals can be enclosed by either single or double, although single quotes are more commonly used.
Open a REPL (read–eval–print loop) or interactive shell to start exploring Python strings:
$ python3.6
- We create strings using either single quotes (
'
), double quotes ("
), or triple single or double quotes for a multi-line string:
>>> 'single quoted string'
'single quoted string'
>>> "double quoted string"
'double quoted string'
>>> '''
... this is a triple
... quoted string
... '''
'\nthis is a triple\nquoted string\n'
Strings also work with some arithmetic operators.
We can combine strings using the +
operator and multiply a string by a number using the *
operator:
>>> "pass" + "word"
'password'
>>> "Ha" * 4
'HaHaHaHa'
We need to cover the concept of an “Object” in object-oriented programming before moving on.
An “object” encapsulates two things:
- State
- Behavior
For the built-in types, the state makes sense because it’s the entire contents of the object. The behavior aspect means that there are functions that we can call on the instances of the objects that we have. A function bound to an object is called a “method”. Here are some example methods that we can call on strings:
find
locates the first instance of a character (or string) in a string. This function returns the index of the character or string:
>>> "double".find('s')
-1
>>> "double".find('u')
2
>>> "double".find('bl')
3
lower
converts all of the characters in a string to their lowercase versions (if they have one). This function returns a new string without changing the original, and this becomes important later:
>>> "TeStInG".lower() # "testing"
'testing'
>>> "another".lower()
'another'
>>> "PassWord123".lower()
'password123'
Lastly, if we need to use quotes or special characters in a string we can do that using the ‘’
' character:
That’s all!
Hope you like the article. Please let me know your feedback in the response section.
Thanks. Happy learning!