SoFunction
Updated on 2025-03-03

Share practical skills for python string processing

Summary of practical skills for Python string processing

Python is a powerful programming language that is particularly good at handling strings. String processing is a very common task in daily programming, so mastering some practical techniques can improve the efficiency and readability of the code. This article will summarize some practical tips for Python string processing and demonstrate them through code examples.

1. Use the string method split() to split the string

split()The method can split the string according to the specified delimiter and return a list containing the divided substrings.

sentence = "Python is awesome"
words = ()  # By default, split by spaceprint(words)  # Output: ['Python', 'is', 'awesome']
# Split strings by commascsv = "apple,banana,orange"
items = (',')
print(items)  # Output: ['apple', 'banana', 'orange']

2. Use the string method join() to connect the string list

join()Methods can concatenate strings in the list and separate them with the specified delimiter.

words = ['Python', 'is', 'awesome']
sentence = ' '.join(words)  # Connect with spacesprint(sentence)  # Output: Python is awesome
items = ['apple', 'banana', 'orange']
csv = ','.join(items)  # Connect with commasprint(csv)  # Output: apple,banana,orange

3. Use string method strip() to remove whitespace characters on both sides of the string

strip()Methods can remove whitespace characters such as spaces, tabs, etc. on both sides of the string.

s = "   hello world   "
cleaned = ()
print(cleaned)  # Output: hello world

4. Use list comprehensions or generator expressions to process string lists

List comprehensions and generator expressions are very convenient tools in Python that can be used to handle string lists.

# List comprehension, convert elements in string list to uppercasewords = ['hello', 'world', 'python']
upper_words = [() for word in words]
print(upper_words)  # Output: ['HELLO', 'WORLD', 'PYTHON']
# Generator expression, only strings with lengths greater than 5 are retainedlong_words = (word for word in words if len(word) > 5)
print(list(long_words))  # Output: ['python']

5. Use the string methods startswith() and endswith() to check the beginning and ends with the string

startswith()andendswith()Methods can be used to check whether a string begins or ends with a specified prefix or suffix.

filename = ""
print(("ex"))  # Output: Trueprint((".txt"))  # Output: True

6. Use the string method replace() to replace the substring in the string

replace()Methods can be used to replace the specified substring in a string.

s = "Hello, World!"
new_s = ("World", "Python")
print(new_s)  # Output: Hello, Python!

7. Use the string method find() or index() to find the location of the substring

find()The method can return the position where the substring first appears in the string, and if it is not found, it returns -1;index()The method is also to find the location of the substring, but an exception will be thrown if it is not found.

s = "Hello, World!"
print(("World"))  # Output: 7print(("Python"))  # Output: -1
print(("World"))  # Output: 7# print(("Python")) # ValueError exception will be thrown

8. Use string method count() to count the number of times substrings appear

count()Methods can count the number of times a substring appears in a string.

s = "hello hello world"
print(("hello"))  # Output: 2

9. Use slice operation to intercept substrings

Python slice operation is very convenient and can be used to intercept substrings in strings.

s = "Hello, World!"
substring = s[7:12]
print(substring)  # Output: World

10. Use regular expressions for complex string matching and replacement

When dealing with complex string matching and replacement, you can use Python'sreModules to operate regular expressions.

import re

s = "hello 123 world 456"
numbers = (r'\d+', s)
print(numbers)  # Output: ['123', '456']
new_s = (r'\d+', '###', s)
print(new_s)  # Output: hello ### world ###

11. Use the string methods startswith() and endswith() to determine whether the string starts or ends with the specified prefix or suffix.

These two methods can help us quickly determine whether a string starts or ends with a certain prefix or suffix.

filename = ""
print(("ex"))  # Output: Trueprint((".txt"))  # Output: True

12. Use string methods isalpha(), isdigit() and isalnum() to determine the type of string

These methods can help us determine whether a string contains only letters, numbers, or combinations of letters and numbers.

s1 = "hello"
s2 = "123"
s3 = "hello123"
s4 = "hello 123"

print(())  # Output: Trueprint(())  # Output: Trueprint(())  # Output: Trueprint(())  # Output: False

13. Use the string methods lower() and upper() to convert the string to lowercase or uppercase

These two methods can conveniently convert strings to lowercase or uppercase form.

s = "Hello, World!"
print(())  # Output: hello, world!print(())  # Output: HELLO, WORLD!

14. Use string methods capitalize() and title() to capitalize the first letter of the string or the first letter of each word

These two methods can help us normalize the format of strings.

s = "hello world"
print(())  # Output: Hello worldprint(())  # Output: Hello World

15. Align strings using string methods center(), ljust() and rjust()

These methods allow the string to be centered, left-aligned, or right-aligned within the specified width.

s = "hello"
print((10, '*'))  # Output: **hello***print((10, '-'))  # Output: hello----print((10, '='))  # Output: =====hello

16. Use the string method splitlines() to split strings by line

splitlines()The method can split the string by line and return a list containing the contents of each line.

text = "Hello\nWorld\nPython"
lines = ()
print(lines)  # Output: ['Hello', 'World', 'Python']

17. Use the string methods partition() and rpartition() to split the string

partition()The method can divide the string into three parts according to the specified delimiter, returning a tuple containing the split result;rpartition()The division starts from the right.

s = "hello world python"
parts = (" ")
print(parts)  # Output: ('hello', '', 'world python')
parts = (" ")
print(parts)  # Output: ('hello world', '', 'python')

18. Use string method zfill() to fill in zeros in front of a numeric string

zfill()The method can fill zeros on the left side of the numeric string to reach the specified width.

number = "42"
padded_number = (5)
print(padded_number)  # Output: 00042

19. Use string method swapcase() to swap case in string

swapcase()Methods can swap case in strings.

s = "Hello, World!"
print(())  # Output: hELLO, wORLD!

20. Use the string method translate() to replace characters in the string

translate()Methods can replace characters in strings based on the specified mapping table.

translation_table = ("aeiou", "12345")
s = "hello world"
new_s = (translation_table)
print(new_s)  # Output: h2ll4 w4rld

Summarize

This article summarizes a series of very practical tips when handling strings in Python:

  1. usesplit()andjoin()Methods to split and concatenate strings.
  2. usestrip()Method to remove whitespace characters on both sides of the string.
  3. Use list comprehensions and generator expressions to process string lists.
  4. usestartswith()andendswith()Method checks the beginning and end of the string.
  5. usereplace()Method replaces substrings in strings.
  6. usefind()andindex()Method to find the location of the substring.
  7. usecount()Method counts the number of times the substring appears.
  8. Use the slice operation to cut the substring.
  9. Use regular expressions for complex string matching and replacement.
  10. Utilizeisalpha()isdigit()andisalnum()Method determines the type of string.
  11. uselower()andupper()Method converts strings to lowercase or uppercase.
  12. usecapitalize()andtitle()Method capitalizes the initial letter of a string or the initial letter of each word.
  13. usecenter()ljust()andrjust()Methods align strings.
  14. usesplitlines()Method splits strings by line.
  15. usepartition()andrpartition()Method splitting strings.
  16. usezfill()Method fills zeros before the numeric string.
  17. useswapcase()Method swap case in strings.
  18. usetranslate()Method replaces characters in a string.

These techniques can help developers handle various string operations more efficiently and flexibly, improving the efficiency and readability of their code. By mastering these techniques, it is easier to solve string processing problems encountered in daily programming.

The above is the detailed content shared by practical ython string processing techniques. For more information about ython string processing techniques, please pay attention to my other related articles!