Skip to main content

Command Palette

Search for a command to run...

๐Ÿ’ป Python Strings Methods

Published
โ€ข2 min read
S

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)

MethodWhat it DoesExample
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 stringlen("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

EscapeMeaning
\nNew line
\tTab 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