Basic Python String Syntax and Operations
1. String Syntax
Syntax:
'single quoted string'
"double quoted string"
'''triple quoted
multiline string'''
"""another multiline
string"""
Explanation:
- Strings in Python are sequences of Unicode characters.
- They can be enclosed in single, double, or triple quotes.
- Triple quotes allow multiline strings.
Example:
s1 = 'Hello'
s2 = "World"
s3 = '''This is
a multiline string'''
2. Common String Methods
Explanation:
- String methods are built-in functions used to perform operations on strings.
- Strings are immutable; methods return new strings without changing the original.
1. upper()
Explanation: Converts all characters to uppercase.
Example:
s = 'hello'
print([Link]()) # Output: 'HELLO'
2. lower()
Explanation: Converts all characters to lowercase.
Example:
s = 'HELLO'
print([Link]()) # Output: 'hello'
3. capitalize()
Explanation: Capitalizes the first character of the string.
Example:
s = 'python'
print([Link]()) # Output: 'Python'
4. title()
Explanation: Capitalizes the first letter of each word.
Example:
s = 'hello world'
print([Link]()) # Output: 'Hello World'
5. strip()
Explanation: Removes leading and trailing spaces.
Example:
s = ' hello '
print([Link]()) # Output: 'hello'
6. replace()
Explanation: Replaces a substring with another.
Example:
s = 'apple'
print([Link]('a', 'A')) # Output: 'Apple'
7. find()
Explanation: Returns the index of first occurrence of a substring.
Example:
s = 'banana'
print([Link]('a')) # Output: 1
8. count()
Explanation: Counts the number of times a substring appears.
Example:
s = 'banana'
print([Link]('a')) # Output: 3
9. split()
Explanation: Splits string into a list by delimiter (default space).
Example:
s = 'a b c'
print([Link]()) # Output: ['a', 'b', 'c']
10. join()
Explanation: Joins elements of a list into a string.
Example:
lst = ['a', 'b', 'c']
print('-'.join(lst)) # Output: 'a-b-c'
11. startswith()
Explanation: Checks if string starts with a given prefix.
Example:
s = 'hello'
print([Link]('he')) # Output: True
12. endswith()
Explanation: Checks if string ends with a given suffix.
Example:
s = 'hello'
print([Link]('lo')) # Output: True