Strings are sequences of characters.
Strings can be written in the following ways:
- ‘single quotes’
- “double quotes”
- ”‘multi line”’
Escape sequences are used to display characters with a special meaning such as
\ within a string.
\ndisplays a new line (LF)
Further reading about escape sequences here.
To find the length a string, the
len() function can be used.
To convert other datatypes to a string, the
str() function can be used.
mystr=str(100) type(mystr) <class 'str'>
There are built in methods available to perform common operations/transformations in Python. Some of them can be found here. I won’t show the usage of the functions here though.
I will talk about slicing strings very briefly. A slice is a segment of the string. The following code demonstrates how to slice a string.
slice_example='string contents' print(slice_example[3:12]) ing conte print(slice_example[:10]) string con print(slice_example[4:]) ng contents
[n:m] returns the string from the n-th character to the m-th character, including the n-th character and excluding the m-th character. If
n is omitted, it starts from the first character. If
m is omitted, it ends with the last character.
An important property of strings is that, they are immutable. The following example demonstrates this property.
s='abc' s='x' TypeError: 'str' object does not support item assignment
To learn more about text processing refer this link.
A quick note about why I am not explaining all the string processing services and string methods: I just need to know, at a high level, what string processing resources exist and where to find them when the need arises. Spending time trying out all the methods and services is not very efficient or interesting. Let me reiterate that I will be learning on the fly.
Code for today’s plog is available here.