Strings
String¶
A string is a sequence of characters enclosed in quotes.
In [1]:
Copied!
# using single quotes
first_name = 'Nirajan'
print(first_name)
# using double quotes
last_name = "Bekoju"
print(last_name)
# Triple quotes for multi-line
tutorial = """
I am learning Python.
Python is fun.
"""
print(tutorial)
# using single quotes
first_name = 'Nirajan'
print(first_name)
# using double quotes
last_name = "Bekoju"
print(last_name)
# Triple quotes for multi-line
tutorial = """
I am learning Python.
Python is fun.
"""
print(tutorial)
Nirajan Bekoju I am learning Python. Python is fun.
Characteristics 1 : Strings can be indexed or sliced.¶
In [2]:
Copied!
## index example
text = 'Python'
print(len(text))
print(text[0])
print(text[3])
## index out of range
print(text[9])
## index example
text = 'Python'
print(len(text))
print(text[0])
print(text[3])
## index out of range
print(text[9])
6 P h
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[2], line 8 5 print(text[3]) 7 ## index out of range ----> 8 print(text[9]) IndexError: string index out of range
In [3]:
Copied!
## index example using negative value
text = 'Python'
print(text[-1])
print(text[-2])
print(text[-3])
print(text[-11])
## index example using negative value
text = 'Python'
print(text[-1])
print(text[-2])
print(text[-3])
print(text[-11])
n o h
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[3], line 7 4 print(text[-2]) 5 print(text[-3]) ----> 7 print(text[-11]) IndexError: string index out of range
In [4]:
Copied!
### string slicing
text = 'Python'
print(text[0:4])
print(text[2:8])
print(text[2:])
print(text[:5])
### string slicing
text = 'Python'
print(text[0:4])
print(text[2:8])
print(text[2:])
print(text[:5])
Pyth thon thon Pytho
In [6]:
Copied!
text = 'Python'
print(text[-3:])
print(text[-3:-5])
print(text[-4:-2])
text = 'Python'
print(text[-3:])
print(text[-3:-5])
print(text[-4:-2])
hon th
In [7]:
Copied!
text = 'abcdefghij'
print(len(text))
print(text[0:5])
print(text[0:5:2])
text = 'abcdefghij'
print(len(text))
print(text[0:5])
print(text[0:5:2])
10 abcde ace
In [9]:
Copied!
text = 'abcdefghij'
print(text[::-1])
print(text[::-2])
text = 'abcdefghij'
print(text[::-1])
print(text[::-2])
jihgfedcba jhfdb
String Concatenation¶
In [11]:
Copied!
first_name = 'Toni'
last_name = 'Kroos'
concatenated_word = first_name + ' ' + last_name
print(concatenated_word)
## also calculate the length of the concatenated word
print(len(concatenated_word))
first_name = 'Toni'
last_name = 'Kroos'
concatenated_word = first_name + ' ' + last_name
print(concatenated_word)
## also calculate the length of the concatenated word
print(len(concatenated_word))
Toni Kroos 10
Characteristics 2 : Strings are immutable.¶
- Immutable means they cannot be changed after creation
In [12]:
Copied!
a = 'Hello World'
print(id(a))
a[1] = 'b'
print()
a = 'Hello World'
print(id(a))
a[1] = 'b'
print()
131676183822896
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[12], line 3 1 a = 'Hello World' 2 print(id(a)) ----> 3 a[1] = 'b' 4 print() TypeError: 'str' object does not support item assignment
In [25]:
Copied!
a = 'random string 1'
print(id(a))
a = 'random string 1'
print(id(a))
123290813869040
In [26]:
Copied!
a = 'hello world'
print(id(a))
a = 'hello world'
print(id(a))
123290813873776
String Methods¶
String Method Exercise¶
Take a name from the user and print it in uppercase and lowercase.
Count how many times the letter "a" appears in the string "banana".
Check if a user-entered word starts with "A" or ends with "z".
Write a program that takes a full name and splits it into first and last name.
Take a input string from user and print its reverse
Method | Description | Example |
---|---|---|
str.lower() |
Converts to lowercase | "Hello".lower() → 'hello' |
str.upper() |
Converts to uppercase | "hello".upper() → 'HELLO' |
str.title() |
Capitalizes first letter of each word | "hello world".title() -> Hello World |
str.capitalize() |
Capitalizes the first character | "hello".capitalize() → 'Hello' |
str.strip() |
Removes leading/trailing spaces | " hello ".strip() |
str.replace(old, new) |
Replaces a substring | "apple".replace("a", "A") |
str.find(sub) |
Finds the first index of substring | "hello".find("l") → 2 |
str.count(sub) |
Counts occurrences of a substring | "banana".count("a") → 3 |
str.split(sep) |
Splits string into a list | "a,b,c".split(",") |
str.join(list) |
Joins list into a string | " ".join(["I", "love", "Python"]) |
str.isalpha() |
Checks if all characters are alphabetic | "abc".isalpha() → True |
str.isdigit() |
Checks if all characters are digits | "123".isdigit() → True |
str.isalnum() |
Checks if alphanumeric | "abc123".isalnum() → True |
str.startswith(prefix) |
Checks if string starts with prefix |
"hello".startswith("he") |
str.endswith(suffix) |
Checks if string ends with suffix |
"hello".endswith("o") |
In [15]:
Copied!
name = 'kroos toni abc sk'
title_name = name.title()
print(title_name)
name = 'kroos toni abc sk'
title_name = name.title()
print(title_name)
Kroos Toni Abc Sk
In [14]:
Copied!
print(name)
print(name)
kroos toni abc sk
In [32]:
Copied!
name = 'Rejesh Hamal'
# replace e with a
name.replace('e', 'a', 1)
name = 'Rejesh Hamal'
# replace e with a
name.replace('e', 'a', 1)
Out[32]:
'Rajesh Hamal'
In [36]:
Copied!
a = name.lower()
print(a)
print(name)
a = name.lower()
print(a)
print(name)
rejesh hamal Rejesh Hamal
In [37]:
Copied!
name.title()
name.title()
Out[37]:
'Rejesh Hamal'
In [38]:
Copied!
'nirajan BEKOJU'.title()
'nirajan BEKOJU'.title()
Out[38]:
'Nirajan Bekoju'
In [39]:
Copied!
"asdf".isalnum()
"asdf".isalnum()
Out[39]:
True
Escape Characters¶
Character | Description |
---|---|
\n |
New Line |
\t |
Tab |
\\ |
Backslash |
\' |
Single Quote |
\" |
Double Quote |
In [40]:
Copied!
print("Hello I am learning \n Python")
print("Hello I am learning \n Python")
Hello I am learning Python
In [44]:
Copied!
print("Hello I am learning \"python\"")
print("Hello I am learning \"python\"")
Hello I am learning "python"
F-String and Format¶
In [51]:
Copied!
name = 'Rajesh Hamal'
age = 50
temp = "temporary"
new_sentence = f"my name is {name} and I am {age} year old. {temp}"
print(new_sentence)
name = 'Rajesh Hamal'
age = 50
temp = "temporary"
new_sentence = f"my name is {name} and I am {age} year old. {temp}"
print(new_sentence)
my name is Rajesh Hamal and I am 50 year old. temporary
In [53]:
Copied!
name = 'Rajesh Hamal'
age = 50
temp = "temporary"
new_sentence = "My name is {n} and I am {a} year old".format(n = name, a = age)
print(new_sentence)
name = 'Rajesh Hamal'
age = 50
temp = "temporary"
new_sentence = "My name is {n} and I am {a} year old".format(n = name, a = age)
print(new_sentence)
My name is Rajesh Hamal and I am 50 year old
Note : f-string is faster than .format() and hence use it.
In [ ]:
Copied!