KDB中下划线填充字符串:除给定方法外的左右填充替代方案?
Great question! Beyond the rotate-based method you shared, there are several cleaner, more intuitive ways to pad underscores to the left or right of a string in kdb+/q. Let's walk through them with examples using your sample string a:"Apple":
Left-padding Underscores
Method 1: Use # (Take) with Fill Character
This is one of the most idiomatic approaches in q. By first setting the fill character of the string to underscores, we can use # to extend the string to our desired total length, which automatically pads on the left:
q)a:"Apple" q)12#"_"^a // Pad to total length 12, underscores on left "_______Apple"
How it works: "_"^a sets the string's fill character to _, and 12# extends the string to 12 characters—since the original string is only 5 characters long, the remaining 7 positions are filled with underscores on the left.
Method 2: Explicit Concatenation with raze
If you want direct control over the number of padding characters, calculate how many underscores you need and concatenate them with the original string using raze:
q)padLength:12 - count a // 12 total length minus 5 characters in "Apple" q)raze padLength#"_" , a "_______Apple"
Here, padLength#"_" creates a string of 7 underscores, and raze combines it with a into a single string.
Method 3: Format String with format
Use q's format function to align the string, then replace default spaces with underscores:
q)"_"^format["%12s";a] // %12s right-aligns (pads left with spaces), then replace spaces with _ "_______Apple"
Right-padding Underscores
Method 1: Negative # (Take) with Fill Character
Similar to left-padding, but use a negative number with # to pad on the right:
q)-12#"_"^a // Pad to total length 12, underscores on right "Apple_______"
The negative sign tells q to extend the string by padding characters on the right instead of the left.
Method 2: Explicit Concatenation with raze
Reverse the order of concatenation to add underscores after the original string:
q)raze a , padLength#"_" "Apple_______"
Method 3: Format String with Left Alignment
Use %-12s in format to left-align the string (pad right with spaces), then replace spaces with underscores:
q)"_"^format["%-12s";a] // %-12s left-aligns (pads right with spaces), then replace spaces with _ "Apple_______"
All these methods are more readable than the rotate approach and align with common q idioms for string manipulation.
内容的提问来源于stack exchange,提问作者user9525111

