Login Register






Python Tutorial Chapter3 - String Manipulation filter_list
Author
Message
Python Tutorial Chapter3 - String Manipulation #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
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 syntax

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
Code:
>>>'I\'m your beloved prince'
The " \ " is the escape character Smile

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 implicitly
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\)
Code:
>>> print("Here temperature " + str(temp))Here temperature 50 >>> print("Here temperature "+repr(temp)) Here temperature 50
Quote:>>> print 'Temperature is ' + `temp`
Temperature is 50
One unfortunate thing is backtick do not work on python 3.

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 mode

Raw strings are the strings with green colors
Eg.
>>> print("Hello \n4sectors")

Will output
Code:
Hello 4sectors

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”.
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 storm
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….
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 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.
Code:
>>> name = 'maharsen' >>> location = 'northwest' >>> print(‘The cyclone {0} is now currently located @ {1}.format(name,location)) The cyclone maharsen is now currently located @ northwest
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. Biggrin

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') 6

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.
Code:
>>> greetz = "4sectors – Hello geeks greetz MHU from 4sectors" >>> greetz.find('4sectors',1) 19

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:
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']
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:
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. Smile
- 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~

Reply

RE: Python Tutorial Chapter3 - String Manipulation #2
Great tutorial. I'm seeing a lot of Python based content lately which is great. It's a brilliant language especially for beginners.



Reply

RE: Python Tutorial Chapter3 - String Manipulation #3
Nice and cool python guide on String Manipulation. Good Work ^_^
[Image: OilyCostlyEwe.gif]

Reply

RE: Python Tutorial Chapter3 - String Manipulation #4
@3r3bu$ @Psycho_Coder
Thanks bros Smile
Glad you like it.

Reply

RE: Python Tutorial Chapter3 - String Manipulation #5
Don't mind my comment please! I'm just trying to improve your thread:

1) In the Single-Quoted Strings and Escaping Quotes, you presented the solution to the error but you did not mention or specify that the \ is the Escape Character

2) The def you gave under Long String, Raw String, Unicode String which is Because \n is a new-line, it's confusing isn't it? Beginners will think you'll have to insert a space. mention that it's a New Line Character not just new-line

Overall it's a nice tutorial but I seriously recommend that you make use of White Spaces Smile
My Blog: http://www.procurity.wordpress.com
Donations: 1HLjiSbnWMpeQU46eUVCrYdbkrtduX7snG

Reply

RE: Python Tutorial Chapter3 - String Manipulation #6
(05-28-2013, 06:56 AM)Ex094 Wrote: Don't mind my comment please! I'm just trying to improve your thread:

1) In the Single-Quoted Strings and Escaping Quotes, you presented the solution to the error but you did not mention or specify that the \ is the Escape Character

2) The def you gave under Long String, Raw String, Unicode String which is Because \n is a new-line, it's confusing isn't it? Beginners will think you'll have to insert a space. mention that it's a New Line Character not just new-line

Overall it's a nice tutorial but I seriously recommend that you make use of White Spaces Smile

Thanks a lot bro Smile
You always carefully read my threads.
Thanks for supportive comment.

Reply

RE: Python Tutorial Chapter3 - String Manipulation #7
Actually, you don't even need to escape ' in this part:
Code:
'I\'m your beloved prince'

Why not explain that you could have used double quotes?
Code:
"I'm your beloved prince"

Usually, for the most part, you would need to escape "\" to print an "\" by doubling up, or using it in combination with things like "\n", "\t", etc... Those would have been better examples.

Code:
print">\tTesting"

You should have also explained the most common use for triple quotes. Ex:
Code:
def Func1(x): '''assumes: 0 <= x < 100 return: blah blah ''' return blah blah blah
ArkPhaze
"Object oriented way to get rich? Inheritance"
Getting Started: C/C++ | Common Mistakes
[ Assembly / C++ / .NET / Haskell / J Programmer ]

Reply

RE: Python Tutorial Chapter3 - String Manipulation #8
Thanks for your advices bro Smile
That's alternative ways .

Reply

RE: Python Tutorial Chapter3 - String Manipulation #9
Thanks for your advices bro Smile
That's alternative ways .

Reply