"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.website = "Quillix Blogspot"
print(len(website))
Join String (Concatenation)
FirstName = "John"
LastName = "Smith"
YourName = FirstName + " " + LastName
print(YourName)
Repeat a String
Code = "Python"
print(Code * 3)
Changing Letter Case
Upper and Lower case.Code = "Python"
print(Code.upper())
print(Code.lower())
Checking Text Inside a String
text = "Python Programming"
print("Python" in text) #Output:True
Removing Extra Spaces
strip() method helps user to remove it.Learn = " Python Programming "
print(Learn.strip())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])
find(), count(), split(), etc., which are very helpful in real-world programming. If you found this helpful, feel free to share it with others.
No comments:
Post a Comment