-
Hajipur, Bihar, 844101
Strings in Python are used to store text. A string is a sequence of characters enclosed in single or double quotes.
a = "Hello"
b = 'World'
print(a, b)
Use triple quotes for multiline strings.
text = """This is a
multiline string."""
print(text)
Each character in a string has an index. The first character has index 0.
a = "Python"
print(a[0]) # Output: P
print(a[1]) # Output: y
for letter in "Python":
print(letter)
Use len()
to get the number of characters in a string.
a = "Hello"
print(len(a)) # Output: 5
Use the in
keyword to check if a word or letter is in the string.
text = "Python is fun"
print("fun" in text) # Output: True
a = "Programming"
print(a[0:6]) # Output: Progra
print(a[:4]) # Output: Prog
print(a[4:]) # Output: ramming
text = " Hello World "
print(text.lower()) # hello world
print(text.upper()) # HELLO WORLD
print(text.strip()) # Hello World
print(text.replace("World", "Python")) # Hello Python
print(text.split()) # ['Hello', 'World']
a = "Hello"
b = "Python"
c = a + " " + b
print(c)
Use backslash \
to escape characters.
print("He said \"Hello\"")
Practice string slicing, concatenation, indexing, and built-in methods.
Q1. Write a Python program to create a string and print its first and last characters.
Q2. Write a Python program to slice and print the word "Python"
from the string "I love Python programming"
.
Q3. Write a Python program to use a loop to print each letter in the word "STRING"
.
Q4. Write a Python program to concatenate "Hello"
and "World"
with a space in between and print the result.
Q5. Write a Python program to replace "dog"
with "cat"
in the string "The dog is cute"
.
Q6. Write a Python program to split the sentence "Welcome to Python"
into a list of words.
Q7. Write a Python program to check if the word "code"
exists in the string "codepractice.in"
.
Q8. Write a Python program to convert the string "python programming"
to uppercase.
Q9. Write a Python program to print the length of the string "Technovlogs"
.
Q10. Write a Python program to use an escape character to print: She said "Hi"
.
Q1: What data type is used to store text in Python?
Q2: What does len("abc") return?
Q3: How do you access the first character of a string a = "hello"?
Q4: Which method converts a string to lowercase?
Q5: Which method removes whitespace from both ends of a string?
Q6: What does "a" + "b" produce?
Q7: What is the output of "Hello".upper()?
Q8: What is the use of \n in strings?
Q9: What does "Hello".replace("H", "J") return?
Q10: Which method is used to split a string into a list?