String GGG
String GGG
g
Strings
A string is a sequence of letters (called characters).
In Python, strings start and end with single or double quotes.
>>> “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
Ex-
print(a)
Looping Through the Strings
Ex-
name = “pawan”
for character in name:
print(character)
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.
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
for i in string.whitespace:
for i in string.punctuation:
print(i)
# 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()
### Example:
str1 = "AbcDEfghIJ"
print(str1.upper())
### Output:
ABCDEFGHIJ
lower()
S=“hello world”
### 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"
# 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
### 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"
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"