๐ป Python Strings Methods
Hi! My name is Safia Khatoon. I am complete my Bachelors in Technology from RTC Institute Of Technology. My specialisation in Computer Science and Engineering.I love contributing to Open Source with the help of the skills I gain.
Also, I'm working on my YouTube Channel as well where I teach about DevOps tools and make technical content. You can have a look at it through my profile.
Feel free to reach out to me! I'd be happy to connect with you.
๐น 1. What is a String?
A string is a group of text or characters.
In Python, we use quotes (
''or"") to make a string.
name = "Safia"
greeting = 'Hello World'
๐น 2. How to Create a String?
s1 = "Hello"
s2 = 'Python'
s3 = """With triple quotes,
you can write multi-line strings."""
๐น 3. String Indexing (Access Characters)
- Indexing starts from 0
text = "Python"
print(text[0]) # Output: P
print(text[5]) # Output: n
๐น 4. String Slicing (Access Part of String)
text = "Safia"
print(text[0:3]) # Output: Saf
print(text[:2]) # Output: Sa
print(text[2:]) # Output: fia
๐น 5. Useful String Methods (Functions)
| Method | What it Does | Example |
upper() | Converts to uppercase | "safia".upper() โ "SAFIA" |
lower() | Converts to lowercase | "HELLO".lower() โ "hello" |
strip() | Removes extra spaces | " Hello ".strip() โ "Hello" |
replace(a, b) | Replaces a with b | "hello".replace("h", "j") โ "jello" |
split() | Splits string into list | "a,b,c".split(",") โ ['a', 'b', 'c'] |
join() | Joins list into string | " ".join(['Hello', 'World']) โ "Hello World" |
len() | Tells length of string | len("Python") โ 6 |
๐น 6. String Formatting (Add Variables in String)
name = "Safia"
age = 20
print(f"My name is {name} and I am {age} years old.")
๐น 7. Escape Characters
| Escape | Meaning |
\n | New line |
\t | Tab space |
\' | Single quote |
\" | Double quote |
print("Hello\nWorld")
print("It\'s me, Safia")
๐น 8. Strings are Immutable
- Strings canโt be changed directly.
name = "Safia"
# name[0] = "J" โ Error
name = "Jafia" โ
Make a new string
๐น 9. Looping Through a String
for char in "Safia":
print(char)
๐น 10. Check if Something Exists in String
text = "Python is awesome"
print("Python" in text) # True
print("Java" not in text) # True