[go: up one dir, main page]

0% found this document useful (0 votes)
20 views47 pages

String GGG

Uploaded by

pawan kamal
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)
20 views47 pages

String GGG

Uploaded by

pawan kamal
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/ 47

Strin

g
Strings
 A string is a sequence of letters (called characters).
 In Python, strings start and end with single or double quotes.

 In python, anything that you enclose between single or


double quotation marks is considered a string.

 Strings are used when working with Unicode characters.

>>> “foo”
‘foo’
>>> ‘foo’
‘foo’

Note: It does not matter whether you enclose your strings in single
or double quotes, the output remains the same.
Multiline Strings

If our string has multiple lines, we can create them


like this:

Ex-

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."“”

print(a)
Looping Through the Strings

We can loop through strings using a for loop like this:

Ex-
name = “pawan”
for character in name:
print(character)

Above code prints all the characters in the string


name one by one!
Defining strings
 Each string is stored in the computer’s memory as a list of
characters.
>>> myString = “GATTACA”

myString
-7 -6 -5 -4 -3 -2 -1
Negative Indexing
Python also supports negative indexes. For example, s[-1]
means extract the first element of s from the end (same
as s[len(s)-1])
>>> s[-1]
'g'
>>> s[-2]
'n'
Accessing single characters
 You can access individual characters by using indices in square brackets.

>>> myString = “GATTACA”


>>> myString[0]
‘G’
>>> myString[1]
‘A’
>>> myString[-
1]
‘A’
>>> myString[-2] Negative indices start at
‘C’ the end of the string and
>>>
Traceback
myString[7]
(most recent call last): move left.
File "<stdin>", line 1, in ?
IndexError: string index out of range
String Slicing
Note: This method of specifying the start and end index to
specify a part of a string is called slicing.

pie = "applepie"
print(pie[:5]) #slicing from start
print(pie[5:]) #slicing till end
print(pie[2:6]) #slicing in between
print(pie[-8:]) #slicing using negative index

## output:
apple
pie
plep
applepie
Accessing substrings
>>> myString = “GATTACA”
>>> myString[1:3]
‘AT’
>>> myString[:3]
‘GAT’
>>> myString[4:]
‘ACA’
>>> myString[3:5]
‘TA’
>>> myString[:]
‘GATTACA’
s[i:j:k] extracts
every kth element
starting with index
i (inlcusive) and
More string functionality
>>> len(“GATTACA”) ← Length
7
>>> “GAT” + “TACA”
‘GATTACA’ ← Concatenation
>>> “A” * 10
‘AAAAAAAAAA ← Repeat
>>> “GAT” in “GATTACA”
True
← Substring test
>>> “AGT” in “GATTACA”
False
Special characters
 The backslash is used to Escape Meaning
introduce a special
character. sequenc
e
>>> "He said, "Wow!""
File "<stdin>", line
\\ Backslash
1
"He said, "Wow!"" \’ Single quote
^
SyntaxError: invalid \” Doubl
s
yntax e
>>> quot
"He said, 'Wow!'" e
"He
said, 'Wow!'" \n Newline
String Operations-String Module
 import string
 #returning all letters
 print(string.ascii_letters)
 #returning lowercase letters
 print(string.ascii_lowercase)
 #returning uppercase
letters
 print(string.ascii_uppercase)
 #returning all punctuations
 print(string.punctuation)
 #returning whitespaces
 print(string.whitespace)
 #returning all digits
 print(string.digits)
Try This
'''checking for whitespaces'''

import string

if " " in string.whitespace:


 print(True)


 for i in string.whitespace:

 for i in string.punctuation:
print(i)

 """repr convert special


 character into normal"""
String methods
len()

# Length of a String
We can find the length of a string using len() function.

## Example:

fruit = "mango"
len1 = len(fruit)
print("mango is a", len1, "letter word.")

## output:
mango is a 5 letter word.
upper()

The upper() method converts a string to upper case.

### Example:

str1 = "AbcDEfghIJ"
print(str1.upper())

### Output:

ABCDEFGHIJ
lower()

The lower() method converts a string to lower case.


### Example:
```python
str1 = "AbcDEfghIJ"
print(str1.lower())
```
### Output:
```
abcdefghij
```
count()
The count() method returns the number of times the given value has occurred
within the given string.
### Example:
str2 = "Abracadabra"
countStr = str2.count("a")
print(countStr)
### Output:4

 S=“hello world”

 count(‘substring’,start,end)—count nu. Of occurrences of


substring between start and end. Ex: S.count(‘l’,6,10) returns
1

 S.count(‘l’) returns 3 [default search in all string]


replace()

The replace() method replaces all occurences of a string with another


string.
Example:
```python
str2 = "Silver Spoon"
print(str2.replace("Sp", "M"))
```
### Output:
```
Silver Moon
capitalize()
The capitalize() method turns only the first character of the string to uppercase and the
rest other characters of the string are turned to lowercase. The string has no effect if the
first character is already uppercase.
### Example:
str1 = "hello"
capStr1 = str1.capitalize()
print(capStr1)
str2 = "hello WorlD"
capStr2 = str2.capitalize()
print(capStr2)

### Output:
Hello
Hello world
title()
The title() method capitalizes each first letter of the word within the string.
### Example:
```python
str1 = "He's name is Dan. Dan is an honest man."
print(str1.title())
```
### Output:
```
He'S Name Is Dan. Dan Is An Honest Man.
```
center()
The center() method aligns the string to the center as per the
parameters given by the user.
### Example:
```python
str1 = "Welcome to the Console!!!"
print(str1.center(50))
```
### Output:
```
Welcome to the Console!!!
```
find()
The find() method searches for the first occurrence of the given value and
returns the index where it is present. If given value is absent from the
string then return -1.
### Example:
```pythonn
str1 = "He's name is Dan. He is an honest man."
print(str1.find("is"))
```
### Output:
```
10
```
S.rfind(‘n’)—returns rightmost index of the substring
As we can see, this method is somewhat similar to the index() method. The
major difference being that index() raises an exception if value is absent
whereas find() does not.

### Example:
```python
str1 = "He's name is Dan. He is an honest man."
print(str1.find("Daniel"))
```
### Output:
```
-1
```
index()
The index() method searches for the first occurrence of the given value and
returns the index where it is present. If given value is absent from the string
then raise an exception.
### Example:
```python
str1 = "He's name is Dan. Dan is an honest man."
print(str1.index("Dan"))
```
### Output:
```
13
```
As we can see, this method is somewhat similar to the find() method. The
major difference being that index() raises an exception if value is absent
whereas find() does not.

### Example:
```python
str1 = "He's name is Dan. Dan is an honest man."
print(str1.index("Daniel"))
```
### Output:
```
ValueError: substring not found
```
isalnum()
The isalnum() method returns True only if the entire string only consists of
A-Z, a-z, 0-9. If any other characters or punctuations are present, then it
returns False.
### Example 1:
```python
str1 = "WelcomeToTheConsole"
print(str1.isalnum())
```
Output:
```
True
```
isalpha()
The isalpha() method returns True only if the entire string only consists of
A-Z, a-z. If any other characters or punctuations or numbers(0-9) are
present, then it returns False.
### Example :
```python
str1 = "Welcome"
print(str1.isalpha())
```
### Output:
```
True
```
isdigit()
The isdigit() method returns True only if the entire string only
consists of 0-9 digits.

Example-

str = “2348953”
print(str.isdigit())
Output – True

str1 = “jhhff-27881”
print(str1.isdigit())
Output - False
islower()
## islower() :
The islower() method returns True if all the characters in the string are lower case,
else it returns False.
### Example:
```python
str1 = "hello world"
print(str1.islower())
```
### Output:
```
True
```
isupper()
## isupper() :
The isupper() method returns True if all the characters in the string are upper case,
else it returns False.
### Example:
```python
str1 = "hello World"
print(str1.isupper())
```
### Output:
```
False
```
isprintable()
 The isprintable() method returns True if all the values within the given
string are printable, if not, then return False.
 A character is considered printable if it is a space or any character that has a
visible representation, such as letters, numbers, punctuation, etc.
 Non-printable characters: Control characters like newline (\n), tab (\
t), carriage return (\r), and others (like \x0b or \x0c)

### Example :
str1 = "We wish you a Merry Christmas"
print(str1.isprintable())

### Output:
True
isspace()
The isspace() method returns True only and only if the string contains
white spaces, else returns False.
### Example:
```python
str1 = " " #using Spacebar
print(str1.isspace())
str2 = " " #using Tab
print(str2.isspace())
```
### Output:
```
True
True
```
istitle()
The istitile() returns True only if the first letter of each word of the string
is capitalized, else it returns False.
### Example:
```python
str1 = "World Health Organization"
print(str1.istitle())
```
### Output:
```
True
```
### Example:
```python
str2 = "To kill a Mocking bird"
print(str2.istitle())
```
### Output:
```
False
```
swapcase()
The swapcase() method changes the character casing of the string. Upper
case are converted to lower case and lower case to upper case.
### Example:
```python
str1 = "Python is a Interpreted Language"
print(str1.swapcase())
```
### Output:
```
pYTHON IS A iNTERPRETED lANGUAGE
```
split()
 The split() method with a string argument separates strings based
on the specified delimiter.
 Note 2:With no arguments, split() separates strings using one or
more spaces as the delimiter.
 Return a list

 s = "topeka,kansas city,wichita,olathe"

 # Separate on comma.
 cities = s.split(",")
 Print(cities) #['topeka', 'kansas city', 'wichita', 'olathe']


# Loop and print each city name.

for city in cities:

print(city)
 s = "One two three"

 # Call split with no arguments.


 words = s.split()
 Output-
 ['One', 'two', 'three']

 # Display results.
 for word in words:

 print(word)
Output
 One
 two
 three
rsplit()
 Rsplit. Usually rsplit() is the same as split. The only difference
occurs when the second argument is specified. This limits the
number of times a string is separated.
 So:When we specify 3, we split off only three times from the right.
This is the maximum number of splits that occur. # Data.
 s=
"Buffalo;Rochester;Yonkers;Syracuse;Albany;Schenectady"

 # Separate on semicolon.
 # ... Split from the right, only split three.
 cities = s.rsplit(";", 3)
 Print(cities)


 Output-
 ['Buffalo;Rochester;Yonkers', 'Syracuse', 'Albany', 'Schenectady']
Splitlines()
 Splitlines. Lines of text can be separated with Windows, or UNIX,
newline sequences. This makes splitting on lines complex. The
splitlines() method helps here.
 # Data.
 s = """This string
 has many
 lines."""
 # Split on line breaks.
 lines = s.splitlines()
 # Loop and display each line.
 for line in lines:
 print("[" + line + "]")
 Output
 [ This string ]
 [ has many ]
 [ lines. ]
Join
 Join. This method combines strings in a list or other iterable
collection.
 With join, we reverse the split() operation. We can use a
delimiter
of zero, one or more characters.
 list = ["a", "b", "c"]
 # Join with empty string literal.
 result = "".join(list)
 # Join with comma.
 result2 = ",".join(list)
 # Display results.
 print(result)
 print(result2)
 Output
 abc
 a,b,c
strip()
 With strip, we remove certain characters (such as whitespace)
from the left and right parts of strings. We invoke lstrip, rstrip and
the strip().
 Lstrip:With no argument, lstrip removes whitespace at the start of

the string. The L stands for left.


 Rstrip:With no argument, rstrip removes whitespace at the end.

This is the right side. If no whitespace is present, nothing happens.


the rstrip() removes any trailing characters.
Example:
str3 = "Hello !!!"
print(str3.rstrip("!"))

### Output:
Hello
Example
 # Has two leading spaces and a trailing one.
 value = " a line "
 # Remove left spaces.
 value1 = value.lstrip()
 print("[" + value1 + "]")
 # Remove right spaces.
 value2 = value.rstrip()
 print("[" + value2 + "]")
 # Remove left and right spaces.
 value3 = value.strip()
 print("[" + value3 + "]")
 Output
 [a line ]
 [ a line]
 [a line]
Example
 # Has numbers on left and right, and some syntax.

value = "50342=Data,231"

# Strip all digits.


# ... Also remove equals sign and comma.

result = value.strip("0123456789=,")
print(result)

Output-
Data
rjust and ljust
 Ljust and rjust pad strings. They accept one or two arguments.
The first argument is the total length of the result string. The
second is the padding character.

s = "Paris"
 # Justify to left, add periods.
 print(s.ljust(10, "."))

 # Justify to right.

 print(s.rjust(10))

 #justify center

 print("hello".center(10,"."))

Output
 Paris.....

 Paris
 ..hello...
startswith
 phrase = "cat, dog and bird"

 # See if the phrase starts with these strings.


 if phrase.startswith("cat"):
 Print(True)
 if phrase.startswith("cat,
 dog"):
print(True)
 # It does not start with

this string.
 if not phrase.startswith("elephant"):
print(False)
 Output
 True
 True
 False
endswith
 url = "https://www.rediffmail.com/"

 # Test the end of the url.


 if url.endswith("/"):
 print("Ends with slash")
 if url.endswith(".com/"):
 print("Ends
with .com/")

 if url.endswith("?") ==

False:
# Does not end in a question mark.
print(False)

 Output
Ends with slash
 Ends with .com/
 False

You might also like