String are one of the basic data structures and are utilized for a variety of tasks. Here are some of the most commonly used methods and functions for working with strings, along with some examples (Python Document)

1. String Slicing
text = "Hello, Python!"
# Extract the first 5 characters
print(text[:5]) # "Hello"
# Extract a specific range
print(text[7:13]) # "Python"
# Output strings in reverse order
print(text[::-1]) # "!nohtyP ,olleH"
2. Joining strings
# + Combining strings with operators
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!"
print(message) # "Hello, Alice!"
#Combining strings using join()
words = ["Hello", "Python", "World"]
sentence = " ".join(words)
print(sentence) # "Hello Python World"
3. Repeating a string
text = "Python"
print(text * 3) # "PythonPythonPython"
4. Finding the length of a string
text = "Hello, World!"
print(len(text)) # 13
5. Finding a specific character in a string
text = "Hello, Python!"
# 특정 문자 찾기
print(text.find("P")) # 7 (Where P first appears)
print(text.find("Java")) # -1 (Returns -1 if it doesn't exist)
# index() throws an error if no character is found
print(text.index("P")) # 7
# print(text.index("Java")) # Error occurred
6. Replacing a string
text = "Hello, Python!"
new_text = text.replace("Python", "World")
print(new_text) # "Hello, World!"
7. Split a string (Split)
text = "apple,banana,cherry"
fruits = text.split(",")
print(fruits) # ["apple", "banana", "cherry"]
8. Remove spaces in a string
text = " Hello, World! "
print(text.strip()) # "Hello, World!"
print(text.lstrip()) # "Hello, World! "
print(text.rstrip()) # " Hello, World!"
9. Convert string case
text = "hello, python world"
print(text.upper()) # "HELLO, PYTHON WORLD"
print(text.lower()) # "hello, python world"
print(text.capitalize()) # "Hello, python world"
print(text.title()) # "Hello, Python World"
10. String formatting
name = "Alice"
age = 30
# f-string Formatting
print(f"My name is {name} and I am {age} years old.")
# format() Using methods
print("My name is {} and I am {} years old.".format(name, age))
# % Using operators
print("My name is %s and I am %d years old." % (name, age))
11. String checking (isalpha
, isdigit
, isalnum
)
text = "Hello"
number = "1234"
mixed = "Hello123"
print(text.isalpha()) # True (All Characters)
print(number.isdigit()) # True (All Numbers)
print(mixed.isalnum()) # True (Combinations of letters and numbers)
12. Check if a string contains a specific word
text = "Hello, Python World"
print("Python" in text) # True
print("Java" in text) # False