"Python strings" – We have already seen how to write strings in the previous chapters. In this guide, we will dive deeper into strings to understand how they are used in real programming and explore the different use cases we can create with them.
Learn: Python Data Structure
What is String in Python?
A string is a text format used to store alphabets, symbols, spaces, and numbers. It is a sequence of characters written inside single quotes (' ') or double quotes (" ").
Example:
name = "Quillix Blogspot"city = 'Kanpur'To print a string, we use print function:
Example
text = "Hello World"
print(text) #Output: Hello World
Access String Character
In python string, we can use indexing to acccess a particular string character.
Note: Python indexing starts from '0'.
Example:
website = "Quillix Blogspot"
print(website[2]) # 3rd character
print(website[6]) # 7th character
Find String Length
We can also find the character length of a string in Python using thelen() function.Example
website = "Quillix Blogspot"
print(len(website))
Join String (Concatenation)
Combining two or more strings in Python is an important concept. It also allows us to add default text with user input when displaying messages. We use "+" operator to add string.
ExampleFirstName = "John"
LastName = "Smith"
YourName = FirstName + " " + LastName
print(YourName)
Repeat a String
There is also a method to type same string or text multiple times.
Code = "Python"
print(Code * 3)
Changing Letter Case
In python, we can also change letter in
Upper and Lower case.Code = "Python"
print(Code.upper())
print(Code.lower())
Checking Text Inside a String
Now if we want to check a common word in the string then we can use this method.
text = "Python Programming"
print("Python" in text) #Output:True
Removing Extra Spaces
Consider to left extra between after and before the text then
strip() method helps user to remove it.Learn = " Python Programming "
print(Learn.strip())Using the
Note: The
slice() method, we can extract a desired part of a string.Note: The
slice() method includes the start index but excludes the end index (e.g., index 7 means up to 6).word = "Quillix Python Tutorial"
print(word[0:7])
print(word[8:10])
This is the first part of string operations. In the next tutorial, we will learn some other useful string methods like
find(), count(), split(), etc., which are very helpful in real-world programming. If you found this helpful, feel free to share it with others.
