python string
python string
A string is a sequence of characters enclosed in single (' '), double (" "), or triple (''' ''' or """
""") quotes.
Examples:
python
Copy code
# Single and Double Quotes
str1 = 'Hello'
str2 = "Python"
i. Concatenation (+)
python
Copy code
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # Output: Hello World
python
Copy code
print("Python " * 3) # Output: Python Python Python
python
Copy code
text = "Hello Python"
print("Python" in text) # Output: True
print("Java" not in text) # Output: True
python
Copy code
word = "Programming"
print(len(word)) # Output: 11
i. Positive Indexing
python
Copy code
text = "Python"
print(text[0]) # Output: P
print(text[3]) # Output: h
python
Copy code
text = "Python"
print(text[-1]) # Output: n
print(text[-3]) # Output: h
python
Copy code
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence) # Output: Python is awesome
5. String Methods
i. Changing Case
python
Copy code
text = "Hello World"
python
Copy code
print("Python123".isalnum()) # Output: True (Alphanumeric)
print("Python".isalpha()) # Output: True (Alphabetic)
print("123".isdigit()) # Output: True (Numbers only)
print("hello".islower()) # Output: True
print("HELLO".isupper()) # Output: True
print(" ".isspace()) # Output: True (Whitespace only)
python
Copy code
text = "I love Python"
print(text.find("Python")) # Output: 7 (Index of first occurrence)
print(text.replace("love", "like")) # Output: I like Python
python
Copy code
sentence = "Python is easy to learn"
words = sentence.split() # Splits by space
print(words) # Output: ['Python', 'is', 'easy', 'to', 'learn']
6. Formatting Strings
i. Using format()
python
Copy code
name = "John"
age = 25
sentence = "My name is {} and I am {} years old.".format(name, age)
print(sentence) # Output: My name is John and I am 25 years old.
python
Copy code
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Alice and I am 30 years old.
python
Copy code
name = "Bob"
marks = 90
print("Student: %s, Marks: %d" % (name, marks))
# Output: Student: Bob, Marks: 90