Level 1: Basic String Practice
1. Create a string variable name = "Analytics" and:
o Print its length.
o Print the first and last character.
o Convert it to uppercase and lowercase.
2. Take input from user and:
o Print it in reverse.
o Count number of vowels.
3. Given:
text = "Python is powerful"
o Extract the word "powerful".
o Replace "powerful" with "easy".
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return
a part of the string.
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
Slice From the Start
By leaving out the start index, the range will start at the first character:
Example
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
Slice To the End
Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):
b = "Hello, World!"
print(b[-5:-2])
Upper Case
The upper() method returns the string in upper case:
a = "Hello, World!"
print([Link]())
Lower Case
Example
The lower() method returns the string in lower case:
a = "Hello, World!"
print([Link]())
Remove Whitespace
Whitespace is the space before and/or after the actual text, and very often
you want to remove this space.
Example
The strip() method removes any whitespace from the beginning or the
end:
a = " Hello, World! "
print([Link]()) # returns "Hello, World!"
Replace String
Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print([Link]("H", "J"))
Split String
The split() method returns a list where the text between the specified
separator becomes the list items.
Example
The split() method splits the string into substrings if it finds instances of
the separator:
a = "Hello, World!"
print([Link](",")) # returns ['Hello', ' World!']
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
ExampleGet your own Python Server
Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c=a+b
print(c)
Example
To add a space between them, add a " ":
a = "Hello"
b = "World"
c=a+""+b
print(c)
F-Strings
F-String was introduced in Python 3.6, and is now the preferred way of
formatting strings.
To specify a string as an f-string, simply put an f in front of the string
literal, and add curly brackets {} as placeholders for variables and other
operations.
Example
Create an f-string:
age = 36
txt = f"My name is John, I am {age}"
print(txt)