如何去除字符串解析时的空格?及文本文件数字解析存储问题
Hey there! Let's break down your questions clearly and give you practical, actionable solutions.
1. How to Remove Spaces During String Parsing?
Depending on where the spaces appear and your specific needs, here are a few go-to methods:
- Trim leading/trailing spaces: Use
strip()to wipe whitespace from the start and end of a string. Example:s = " sample string " cleaned_s = s.strip() # Result: "sample string" - Remove all spaces entirely: Use
replace()to swap every space with an empty string:s = "s p a c e d o u t" no_space_s = s.replace(" ", "") # Result: "spacedout" - Collapse and remove all whitespace: If dealing with multiple spaces, tabs, or newlines, combine
split()andjoin()—split()with no arguments splits on any whitespace, then joining with an empty string eliminates all gaps:s = "hello world\nwith\ttabs" cleaned_s = "".join(s.split()) # Result: "helloworldwithtabs" - Regex for complex whitespace patterns: Use the
remodule to replace any sequence of whitespace characters:import re s = " messy string " cleaned_s = re.sub(r"\s+", "", s) # Result: "messystring"
2. Parsing the Numeric Sequence into Three Variables
Since you mentioned using split(), let's use Python to implement this solution step by step.
First, assume your input line (after reading from the text file) looks like this:
line = "1.000000 1:-0.362772 2:-0.314085 3:-0.177185 4:0.898650 5:-0.154588"
Here's how to parse it into your three target variables:
# Split the line into individual segments using spaces as separators parts = line.split() # Convert the first segment to an integer (handle the .000000 format via float first) output = int(float(parts[0])) # Initialize empty lists to store numbers and values number = [] value = [] # Process each number-value pair segment for item in parts[1:]: # Split each item on the colon to separate the number and value strings num_str, val_str = item.split(":") # Convert and append to the respective lists number.append(int(num_str)) value.append(float(val_str))
What this does:
line.split()breaks the full string into a list of segments (e.g.,"1.000000","1:-0.362772", etc.)- Converting
parts[0]viafloat()thenint()safely handles the decimal-formatted initial integer, turning1.000000into1 - Looping through the remaining segments and splitting on
":"lets us separate each number-value pair, convert them to the correct data types, and populate your target lists.
After running this code, you'll have exactly what you need:
output = 1number = [1, 2, 3, 4, 5]value = [-0.362772, -0.314085, -0.177185, 0.898650, -0.154588]
内容的提问来源于stack exchange,提问作者Kim Gary
相关产品推荐
相关产品推荐

