Python Tutorial Chapter3 - String Manipulation 05-28-2013, 04:26 AM
#1
Chapter -3 :> String Manipulation
Now, we are going to talk about String Manipulation. In most Programming languages, basic part is how we can print strings, which is fundamental and important part.
Ok, let’s see
Open up python shell
Python will show up that sentence. This is just ordinary string output.
So, If you want to print strings:
1. Single quote (' ')
2. Double quote (" ")
3. Triple quote(''' ''')
They can be used.
3.1 Single-Quoted Strings and Escaping Quotes
Try below string in shell
Yes, you’ll get that error.
Why? Because there’re three single quotes in that string. The first and the last are opening and closing quotes. In Hello, Guys string that we tried before is using just two single quotes as opening and closing.
Normally, it should be 2 quotes to output string. But now this thing has 3.
Therefore opening and closing are misread by the system.
We can change the single quote to below
The " \ " is the escape character 
3.2 String Concatenation
Strings can be concatenated.
Open up python shell
String can be concatenated like that.
3.3 String Representations, str & repr
Now, we’ll talk about how strings are organized
Try this
That error will occur. Because we got integer value in temp variable, now this print function will output it as string format.
We can change it like this.
1. Str
2. Repr
3. Backtick(` not a backslash\)
3.4 Long String, Raw String, Unicode String
You should have knew how to write long strings.
Just use 3 single Quote ('''). For example
Raw strings are the strings with green colors
Eg.
>>> print("Hello \n4sectors")
Will output
Because \n is a new-line character
Now, raw strings will output those escaped characters as it is. When writing raw-string, you only need to put a “r”.
In python 2
Now, that’s it.
Unicode String
When you want to output Unicode string, just use “u” in place of “r” as in above code.
3.5 String Operations
3.5.1.1 String Formatting
When we want to format strings, we can use as the following example
Now run this…
In place of %s, it will input the values in tuple as in sequence.
(We’ll cover Tuples and dictionaries in detail later.)
‘%s’ is called conversion specifiers. It marks where we need to input the value
3.5.1.2 Template Strings
We have template function in string module. That is very useful in formatting strings.
Now, we will use Dictionary type.
Eg….
The first line imports template from string module.
The second line creates the variable “s” and use the Template(‘’) function.
Then, create “$lan” and “$dude” variable inside the variable “s”
The third line creates dictionary name “d”.
4th line assign the string python
And 5th line assign the string learners
6th line use s.stringfunc(), substitute function is called.
3.5.2 Using format method
Now, we can use string formatting easily. 2 methods are shown. But this is the most popular method.
The two lines create and assign value to two variables namely “name” and “variable”
The third line use print function. And write the sentence that we want to output. We want to show the variable accordingly so index is assigned {0} {1}. It can be assigned in front of the variable as you wish, but you should keep in mind that you need to index it accordingly.
PS: You can take it as x.attribute. x maybe a string or list.
Attribute tells what needs to be done.
3.5.3 More String Operations
PS: Byte of python does not have much about this topic.
Beginning python from Novice to Professional is more complete.
And when you have digested Python Manual compiled html, you became an expert in python
But…. Is that easy?
No, so we need to learn by bits everyday.
3.5.3.1 str.find()
As its name suggest, it is used to find something from a string. For instance
In this code, first we insert a string into greetz variable.
Then as x.attrib format, we use find.
When we count the word ‘4sectors’ from right, it’s on the 6th index. So the output is 6.
Additional info : You can use ‘find’ to search for keyword with the starting point and ending point. But only starting point is necessary.
Why python didn’t show 0 when we have the keyword ‘4sectors’ in 0 index? It’s because, we make it skip the first one that it found. So it shows the second word that matches keyword. 19
3.5.3.2 str.join()
The function find and join are important functions with string operations.
Syntax of str.join() is
str = the original string
join(x) = the string to be joined with the original
Example:
In the first line, we input 1,2,3 into seq variable as tuple.
Second line input ‘+’ into sep variable.
Third line, uses str.join(x)… yes there is error.
Why? Read the error message. The values in seq variable is int type. That’s why the TypeError message occur.
Then you should be able to understand the modified code below the original.
3.5.3.2 str.split()
This is the reverse of join. If you understand join, then it’s a piece of cake to understand this.
Let’s do an example
First we create dir variable with a simple *nix directory format. Then using split function, we take out ‘/’ (forward slash). It will output automatically with tuple data type. You just need to index it to use.
PS : If no value is provided in split(), join() then it will operate the whitespaces.
3.5.3.2 str.strip()
Now, let’s move on to a new method.
This is used to strip out the unnecessary spaces at the start and end of the string, but not in the middle of the string. The spaces in the middle of the string are untouched.
Eg:
The above string has whitespaces in the right and left of the string. So it was stripped out.
Try to take out the word that you don’t like.
3.6 Summary
- You should be able to handle string operations.
- I think this time the thread is a bit long
Thanks a lot to my little bro "Zero" for English conversion
Regards
Mr.Geek@HC:#logout~
Now, we are going to talk about String Manipulation. In most Programming languages, basic part is how we can print strings, which is fundamental and important part.
Ok, let’s see
Open up python shell
Code:
>>> 'Hello,Guys'
'Hello,Guys'Python will show up that sentence. This is just ordinary string output.
So, If you want to print strings:
1. Single quote (' ')
2. Double quote (" ")
3. Triple quote(''' ''')
They can be used.
3.1 Single-Quoted Strings and Escaping Quotes
Try below string in shell
Code:
>>>'I'm your beloved prince'
SyntaxError: invalid syntaxYes, you’ll get that error.
Why? Because there’re three single quotes in that string. The first and the last are opening and closing quotes. In Hello, Guys string that we tried before is using just two single quotes as opening and closing.
Normally, it should be 2 quotes to output string. But now this thing has 3.
Therefore opening and closing are misread by the system.
We can change the single quote to below
Code:
>>>'I\'m your beloved prince'
3.2 String Concatenation
Strings can be concatenated.
Open up python shell
Code:
>>> x="Hello"
>>> y="Defacer!"
>>> x+y
'HelloDefacer!'String can be concatenated like that.
3.3 String Representations, str & repr
Now, we’ll talk about how strings are organized
Try this
Code:
>>> temp = 50
>>> print "The temperature is " + temp
Traceback (most recent call last):
File “<pyshell#6>”, line 1, in <module>
Print("The temp is " + temp)
TypeError: Can’t covert ‘int’ object to str implicitlyWe can change it like this.
1. Str
2. Repr
3. Backtick(` not a backslash\)
Code:
>>> print("Here temperature " + str(temp))Here temperature 50
>>> print("Here temperature "+repr(temp))
Here temperature 50Quote:>>> print 'Temperature is ' + `temp`One unfortunate thing is backtick do not work on python 3.
Temperature is 50
3.4 Long String, Raw String, Unicode String
You should have knew how to write long strings.
Just use 3 single Quote ('''). For example
Code:
>>> print('''\
Usage
-h help
-a Attack mode
''')
Usage
-h help
-a Attack modeRaw strings are the strings with green colors
Eg.
>>> print("Hello \n4sectors")
Will output
Code:
Hello
4sectorsBecause \n is a new-line character
Now, raw strings will output those escaped characters as it is. When writing raw-string, you only need to put a “r”.
Code:
>>> print(r’Hello \n4sectors’)In python 2
Code:
>>> print r’Hello \n4sectors’Now, that’s it.
Unicode String
When you want to output Unicode string, just use “u” in place of “r” as in above code.
3.5 String Operations
3.5.1.1 String Formatting
When we want to format strings, we can use as the following example
Code:
>>> Format = "Hello %s Geeks. There is a %s"
>>> Values = ('MHU','storm')
Hello MHU Geeks. There is a stormIn place of %s, it will input the values in tuple as in sequence.
(We’ll cover Tuples and dictionaries in detail later.)
‘%s’ is called conversion specifiers. It marks where we need to input the value
3.5.1.2 Template Strings
We have template function in string module. That is very useful in formatting strings.
Now, we will use Dictionary type.
Eg….
Code:
>>> from string import Template
>>> s = Template('We love $lan. We are $dude')
>>> d = {}
>>> d['lan'] = 'python'
>>> d['dude'] = 'learners'
>>> s.substitute(d)
‘We love python. We are learners’The second line creates the variable “s” and use the Template(‘’) function.
Then, create “$lan” and “$dude” variable inside the variable “s”
The third line creates dictionary name “d”.
4th line assign the string python
And 5th line assign the string learners
6th line use s.stringfunc(), substitute function is called.
3.5.2 Using format method
Now, we can use string formatting easily. 2 methods are shown. But this is the most popular method.
Code:
>>> name = 'maharsen'
>>> location = 'northwest'
>>> print(‘The cyclone {0} is now currently located @ {1}.format(name,location))
The cyclone maharsen is now currently located @ northwestThe third line use print function. And write the sentence that we want to output. We want to show the variable accordingly so index is assigned {0} {1}. It can be assigned in front of the variable as you wish, but you should keep in mind that you need to index it accordingly.
PS: You can take it as x.attribute. x maybe a string or list.
Attribute tells what needs to be done.
3.5.3 More String Operations
PS: Byte of python does not have much about this topic.
Beginning python from Novice to Professional is more complete.
And when you have digested Python Manual compiled html, you became an expert in python
But…. Is that easy?
No, so we need to learn by bits everyday.

3.5.3.1 str.find()
As its name suggest, it is used to find something from a string. For instance
Code:
>>> greetz = "Hello 4sectors from HC –"
>>> greetz.find('4sectors')
6In this code, first we insert a string into greetz variable.
Then as x.attrib format, we use find.
When we count the word ‘4sectors’ from right, it’s on the 6th index. So the output is 6.
Additional info : You can use ‘find’ to search for keyword with the starting point and ending point. But only starting point is necessary.
Code:
>>> greetz = "4sectors – Hello geeks greetz MHU from 4sectors"
>>> greetz.find('4sectors',1)
19Why python didn’t show 0 when we have the keyword ‘4sectors’ in 0 index? It’s because, we make it skip the first one that it found. So it shows the second word that matches keyword. 19
3.5.3.2 str.join()
The function find and join are important functions with string operations.
Syntax of str.join() is
str = the original string
join(x) = the string to be joined with the original
Example:
Code:
>>> seq = [1,2,3]
>>> sep = '+'
>>> sep.join(seq)
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
TypeError: sequence item 0: expected string, int found
>>> seq = ['1','2','3']
>>> '+'.join(seq)
‘1+2+3’In the first line, we input 1,2,3 into seq variable as tuple.
Second line input ‘+’ into sep variable.
Third line, uses str.join(x)… yes there is error.
Why? Read the error message. The values in seq variable is int type. That’s why the TypeError message occur.
Then you should be able to understand the modified code below the original.
3.5.3.2 str.split()
This is the reverse of join. If you understand join, then it’s a piece of cake to understand this.
Let’s do an example
Code:
>>> dir = '/usr/bin/4sec'
>>> dir.split('/')
['','usr','bin','4sec']PS : If no value is provided in split(), join() then it will operate the whitespaces.
3.5.3.2 str.strip()
Now, let’s move on to a new method.
This is used to strip out the unnecessary spaces at the start and end of the string, but not in the middle of the string. The spaces in the middle of the string are untouched.
Eg:
Code:
>>> ' __Hello__MHU__ '.strip()
‘__Hello__MHU__’The above string has whitespaces in the right and left of the string. So it was stripped out.
Try to take out the word that you don’t like.
3.6 Summary
- You should be able to handle string operations.

- I think this time the thread is a bit long
Thanks a lot to my little bro "Zero" for English conversion
Regards
Mr.Geek@HC:#logout~




![[+]](https://sinister.li/images/modern/collapse_collapsed.png)
![[Image: OilyCostlyEwe.gif]](http://fat.gfycat.com/OilyCostlyEwe.gif)