[go: up one dir, main page]

0% found this document useful (0 votes)
74 views32 pages

Mming/methods/string Ings - HTM: Quotes

- Strings are a popular data type in Python that can be created using either single or double quotes. Strings support operators like + for concatenation and * for repetition, as well as indexing, slicing, and formatting with variables. Common string methods allow searching, splitting, and modifying strings.

Uploaded by

Arooj Irfan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views32 pages

Mming/methods/string Ings - HTM: Quotes

- Strings are a popular data type in Python that can be created using either single or double quotes. Strings support operators like + for concatenation and * for repetition, as well as indexing, slicing, and formatting with variables. Common string methods allow searching, splitting, and modifying strings.

Uploaded by

Arooj Irfan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Strings

https://www.programiz.com/python-progra
mming/methods/string

www.tutorialspoint.com/python/python_str
ings.htm

realpython.com/python-strings

•Strings are amongst the most popular types in Python.


•We can create them simply by enclosing characters in
quotes.
• Python treats single quotes the same as double quotes.
• Creating strings is as simple as assigning a value to a
variable example −
• String Manipulation
• The sections below highlight the operators, methods, and functions
that are available for working with strings.
• String Operators
• You have already seen the operators + and * applied to numeric
operands in the tutorial on Operators and Expressions in Python.
These two operators can be applied to strings as well.
• The + Operator: The + operator concatenates strings. It
returns a string consisting of the operands joined together
• >>> s = 'foo‘
• >>> t = 'bar‘
• >>> u = 'baz'
• >>> s + t
• 'foobar'
• >>> s + t + u
• 'foobarbaz‘
• >>> print('Go team' + '!!!')
• Go team!!!
The * Operator
• The * operator creates multiple copies of a string. If s is a string and n is an
integer, either of the following expressions returns a string consisting
of n concatenated copies of s:
• s*n
n*s
• Here are examples of both forms:
• >>> s = 'foo.'
• >>> s * 4
• 'foo.foo.foo.foo.'
• >>> 4 * s 'foo.foo.foo.foo.'
• The multiplier operand n must be an integer. You’d think it would be required
to be a positive integer, but amusingly, it can be zero or negative, in which case
the result is an empty string:
• >>> 'foo' * -8 ''
• If you were to create a string variable and initialize it to the empty string by
assigning it the value 'foo' * -8, anyone would rightly think you were a bit daft.
But it would work.
• The in Operator
• Python also provides a membership operator that can be
used with strings. The in operator returns True if the first
operand is contained within the second, and False otherwise:
• >>> s = 'foo'
• >>> s in 'That\'s food for thought.‘
• True
• >>> s in 'That\'s good for now.'
• False
• There is also a not in operator, which does the opposite:
• >>> 'z' not in 'abc'
• True
• >>> 'z' not in 'xyz‘
• False
String Indexing
• Often in programming languages, individual items in an
ordered set of data can be accessed directly using a
numeric index or key value. This process is referred to as
indexing.
• In Python, strings are ordered sequences of character
data, and thus can be indexed in this way. Individual
characters in a string can be accessed by specifying the
string name followed by a number in square brackets ([]).
• String indexing in Python is zero-based: the first
character in the string has index 0, the next has index 1,
and so on. The index of the last character will be the
length of the string minus one.
• For example, a schematic diagram of the indices of the string 'foobar' would
look like this:
• f oobar
• 012345
• string indices
• The individual characters can be accessed by index as follows:
• >>> s = 'foobar‘
• >>> s[0]
• 'f'
• >>> s[1]
• 'o'
• >>> s[3]
• 'b'
• >>> len(s)
• 6
• >>> s[len(s)-1]
• 'r'
• Attempting to index beyond the end of the string
results in an error:
• >>> s[6] Traceback (most recent call last): File
"<pyshell#17>", line 1, in <module> s[6] IndexError:
string index out of range
• String indices can also be specified with negative
numbers, in which case indexing occurs from the
end of the string backward: -1 refers to the last
character, -2 the second-to-last character, and so on.
• Here is the same diagram showing both the positive
and negative indices into the string 'foobar':
• -6 -5 -4 -3 -2 -1
• f o o b a r
• 0 1 2 3 4 5
• Here are some examples of negative indexing:
• >>> s = 'foobar'
• >>> s[-1] 'r'
• >>> s[-2] 'a'
• >>> len(s) 6
• >>> s[-len(s)] 'f'
String Slicing
•Python also allows a form of indexing syntax that extracts substrings
from a string, known as string slicing. If s is a string, an expression of
the form s[m:n] returns the portion of s starting with position m, and
up to but not including position n:
•>>>>>> s = 'foobar'
•>>> s[2:5] 'oba'
•Remember: String indices are zero-based. The first character in a
string has index 0. This applies to both standard indexing and slicing.
•Again, the second index specifies the first character that is not
included in the result—the character 'r' (s[5]) in the example above.
That may seem slightly unintuitive, but it produces this result which
makes sense: the expression s[m:n] will return a substring that is n -
m characters in length, in this case, 5 - 2 = 3.
•If you omit the first index, the slice starts at the beginning of the
string. Thus, s[:m] and s[0:m] are equivalent:
• >>> s = 'foobar'
• >>> s[:4] 'foob'
• >>> s[0:4] 'foob'
• Similarly, if you omit the second index as in s[n:], the slice
extends from the first index through the end of the string. This is
a nice, concise alternative to the more cumbersome s[n:len(s)]:
• >>> s = 'foobar'
• >>> s[2:] 'obar'
• >>> s[2:len(s)] 'obar‘
• For any string s and any integer n (0 ≤ n ≤ len(s)), s[:n] + s[n:] will
be equal to s:
• >>> s = 'foobar'
• >>> s[:4] + s[4:] 'foobar'
• >>> s[:4] + s[4:] == s True
• Omitting both indices returns the original string, in its
entirety. Literally. It’s not a copy, it’s a reference to the
original string:
• >>> s = 'foobar'
• >>> t = s[:]
• >>> id(s) 59598496
• >>> id(t) 59598496
• >>> s is t True
• If the first index in a slice is greater than or equal to the
second index, Python returns an empty string. This is yet
another obfuscated way to generate an empty string, in case
you were looking for one:
• >>> s[2:2] '‘
• >>> s[4:2] '‘
• Negative indices can be used with slicing as well. -1 refers to
the last character, -2 the second-to-last, and so on, just as
with simple indexing. The diagram below shows how to slice
the substring 'oob' from the string 'foobar' using both positive
and negative indices:
• -6 -5 -4 -3 -2 -1
• f o o b a r
• 0 1 2 3 4 5
• Here is the corresponding Python code:
• >>>>>> s = 'foobar' >>> s[-5:-2] 'oob' >>> s[1:4] 'oob' >>> s[-
5:-2] == s[1:4] True
• Specifying a Stride in a String Slice
• There is one more variant of the slicing syntax to discuss. Adding an
additional : and a third index designates a stride (also called a step),
which indicates how many characters to jump after retrieving each
character in the slice.
• For example, for the string 'foobar', the slice 0:6:2 starts with the first
character and ends with the last character (the whole string), and every
second character is skipped. This is shown in the following diagram:
• -6 -5 -4 -3 -2 -1
• f o o b a r
• 0 1 2 3 4 5
• Similarly, 1:6:2 specifies a slice starting with the second character
(index 1) and ending with the last character, and again the stride
value 2 causes every other character to be skipped:
• -6 -5 -4 -3 -2 -1
• f o o b a r
• 0 1 2 3 4 5
• The illustrative REPL code is shown here:
• >>> s = 'foobar'
• >>> s[0:6:2] 'foa'
• >>> s[1:6:2] 'obr'
• As with any slicing, the first and second indices can be omitted, and
default to the first and last characters respectively:
• >>> s = '12345' * 5
• >>> s '1234512345123451234512345'
• >>> s[::5] '11111‘
• >>> s[4::5] '55555'
• You can specify a negative stride value as well, in which case Python
steps backward through the string. In that case, the starting/first
index should be greater than the ending/second index:
• >>> s = 'foobar'
• >>> s[5:0:-2] 'rbo'
• In the above example, 5:0:-2 means “start at the last
character and step backward by 2, up to but not including
the first character.”
• When you are stepping backward, if the first and second
indices are omitted, the defaults are reversed in an
intuitive way: the first index defaults to the end of the
string, and the second index defaults to the beginning.
Here is an example:
• >>> s = '12345' * 5
• >>> s '1234512345123451234512345‘
• >>> s[::-5] '55555'
• This is a common paradigm for reversing a string:
• >>> s = 'If Comrade Napoleon says it, it must be right.' >>>
s[::-1] '.thgir eb tsum ti ,ti syas noelopaN edarmoC fI'
• Interpolating Variables Into a String
• In Python version 3.6, a new string formatting mechanism
was introduced. This feature is formally named the Formatted
String Literal, but is more usually referred to by its
nickname f-string.
• The formatting capability provided by f-strings is extensive
and won’t be covered in full detail here. If you want to learn
more, you can check out the Real Python article 
Python 3’s f-Strings: An Improved String Formatting Syntax (G
uide)
. There is also a tutorial on Formatted Output coming up later
in this series that digs deeper into f-strings.
• One simple feature of f-strings you can start using right away
is variable interpolation. You can specify a variable name
directly within an f-string literal, and Python will replace the
name with the corresponding value.
• For example, suppose you want to display the result of an arithmetic calculation.
You can do this with a straightforward print() statement, separating numeric
values and string literals by commas:
• >>> n = 20
• >>> m = 25
• >>> prod = n * m
• >>> print('The product of', n, 'and', m, 'is', prod)
• The product of 20 and 25 is 500
• But this is cumbersome. To accomplish the same thing using an f-string:
• Specify either a lowercase f or uppercase F directly before the opening quote of
the string literal. This tells Python it is an f-string instead of a standard string.
• Specify any variables to be interpolated in curly braces ({}).
• Recast using an f-string, the above example looks much cleaner:
• >>> n = 20
• >>> m = 25
• >>> prod = n * m
• >>> print(f'The product of {n} and {m} is {prod}')
• The product of 20 and 25 is 500
• Any of Python’s three quoting mechanisms
can be used to define an f-string:
• >>> var = 'Bark'
• >>> print(f'A dog says {var}!')
• A dog says Bark!
• >>> print(f"A dog says {var}!")
• A dog says Bark!
• >>> print(f'''A dog says {var}!''')
• A dog says Bark!
• Modifying Strings
• In a nutshell, you can’t. Strings are one of the data types Python
considers immutable, meaning not able to be changed. In fact, all
the data types you have seen so far are immutable. (Python does
provide data types that are mutable, as you will soon see.)
• A statement like this will cause an error:
• >>> s = 'foobar'
• >>> s[3] = 'x'
• Traceback (most recent call last): File "<pyshell#40>", line 1, in
<module> s[3] = 'x' TypeError: 'str' object does not support item
assignment
• In truth, there really isn’t much need to modify strings. You can
usually easily accomplish what you want by generating a copy of
the original string that has the desired change in place. There are
very many ways to do this in Python. Here is one possibility:
• >>> s = s[:3] + 'x' + s[4:]
• >>> s 'fooxar'
• There is also a built-in string method to
accomplish this:
• >>> s = 'foobar'
• >>> s = s.replace('b', 'x')
• >>> s 'fooxar'
• Read on for more information about built-in
string methods!
• Accessing Values in Strings

• Python does not support a character type; these are treated as


strings of length one, thus also considered a substring.
• To access substrings, use the square brackets for slicing along with the
index or indices to obtain your substring. For example –

• Example 1:
• var1 = 'Hello World!'
• var2 = "Python Programming"
• print "var1[0]: ", var1[0]
• print "var2[1:5]: ", var2[1:5]
• The output of the segment is
• var1[0]: H
• var2[1:5]: ytho
Updating Strings
• You can "update" an existing string by (re)assigning a
variable to another string. The new value can be
related to its previous value or to a completely
different string altogether. For example –
• Example 2:
• var1 = 'Hello World!'
• print "Updated String :- ", var1[:6] + 'Python'
•  
• When the above code is executed, it produces the
following result –
• Updated String :- Hello Python
Escape Characters
• Following table is a list of escape or non-printable characters
that can be represented with backslash notation.
• An escape character gets interpreted; in a single quoted as
well as double quoted strings.
• Backslash notation Description
• \n Newline
•  \r Carriage return
• \t Tab
Example
• print “hello1 Backslash notation"
• print "hello2 \n hello2 Newline"
• print "hello3 \r hello3 Carriage return"
• print "hello4 \t hello4 Tab"
String Special Operators
• Assume string variable a holds 'Hello' and variable b holds 'Python', then −
Operator Description Example
• + Concatenation - Adds values on either side
of the operator a + b will give HelloPython
• * Repetition - Creates new strings, concatenating
multiple copies of the same string a*2 will give –HelloHello
• [] Slice - Gives the character from the given index a[1] will give e
• [ : ] Range Slice - Gives the characters from the
given range a[1:4] will give ell
• In Membership - Returns true if a character exists
in the given string H in a will give 1
• % Format - Performs String formatting See at next section
String Formatting Operator
• One of Python's coolest features is the string format operator %.
This operator is unique to strings and makes up for the pack of
having functions from C's printf() family. Following is a simple
example –

• Example 3:
• print "My name is %s and weight is %d kg!" % ('Zara', 21)
• When the above code is executed, it produces the following result –
• My name is Zara and weight is 21 kg!
 
• Here is the list of complete set of symbols which can be used along
with % −
• Format Symbol Conversion
• %c character
• %s string conversion via str() prior to formatting
• %i signed decimal integer
• %d signed decimal integer
• %u unsigned decimal integer
• %o octal integer
• %x hexadecimal integer (lowercase letters)
• %X hexadecimal integer (UPPERcase letters)
• %e exponential notation (with lowercase 'e')
• %E exponential notation (with UPPERcase 'E')
• %f floating point real number
• %g the shorter of %f and %e
• %G the shorter of %f and %E
Other supported symbols and functionality are listed in the
following table −
Symbol Functionality
* argument specifies width or precision
- left justification
+ display the sign
<sp> leave a blank space before a positive number
# add the octal leading zero ( '0' ) or
hexadecimal leading '0x' or '0X', depending
on whether 'x' or 'X' were used.
0 pad from left with zeros (instead of spaces)
% '%%' leaves you with a single literal '%'
(var) mapping variable (dictionary arguments)
m.n. m is the minimum total width and n is the
number of digits to display after the decimal
point (if appl.)
Triple Quotes
• Python's triple quotes comes to the rescue by allowing strings
to span multiple lines, including verbatim NEWLINEs, TABs,
and any other special characters.
• The syntax for triple quotes consists of three
consecutive single or doublequotes.
• Example 4:
para_str = """this is a long string that is made up of several
lines and non-printable characters such as TAB (\t) and they
will show up that way when displayed. NEWLINEs within the
string, whether explicitly given like this within the brackets
[\n], or just a NEWLINE within the variable assignment will
also show up."""
• print (para_str)
Output of the program
this is a long string that is made up of several lines and non-
printable characters such as TAB ( ) and they will show up that
way when displayed. NEWLINEs within the string, whether
explicitly given like this within the brackets [
], or just a NEWLINE withinthe variable assignment will also show
up.
 
• Raw strings do not treat the backslash as a special character at all.
Every character you put into a raw string stays the way you wrote it

• print 'C:\\nowhere'
• C:\nowhere
• print r'C:\\nowhere‘
• C:\\nowhere
Unicode String
• Normal strings in Python are stored internally as 8-bit
ASCII, while Unicode strings are stored as 16-bit Unicode.
• This allows for a more varied set of characters, including
special characters from most languages in the world.
• I'll restrict my treatment of Unicode strings to the
following −
• print u'Hello, world!'
• When the above code is executed, it produces the
following result −
• Hello, world!
• As you can see, Unicode strings use the prefix u, just as
raw strings use the prefix r.
• Built-in String Methods
Python includes the following built-in methods to manipulate strings
• Python String capitalize() Method
It returns a copy of the string with only its first character capitalized.
Syntax
str.capitalize()
• Example:
str = "this is string example....wow!!!";
print "str.capitalize() : ", str.capitalize()
• Result:
• str.capitalize() : This is string example....wow!!!
• Python String lower() Method
Syntax:
• str.lower()
• Example:
• Str = "THIS IS STRING EXAMPLE....WOW!!!"; print str.lower()
• Result:
• this is string example....wow!!!
• Python String upper() Method
• The method upper() returns a copy of the string in which all case-based characters have
been uppercased.
• Syntax:
str.upper()
• Example:
str = "this is string example....wow!!!";
print "str.capitalize() : ", str.upper()
Result:
str.capitalize() : THIS IS STRIN EXAMPLE....WOW!!!

• Python String len() Method


• The method len() returns the length of the string.
• Syntax:
len( str )
• Example:
str = "this is string example....wow!!!";
print "Length of the string: ", len(str)
Result −
Length of the string: 32

You might also like