[PYTHON] Various character string operations

Fill

Right justified

python


print "{:<10}".format("python")
# => "python    "

print "{:!<10}".format(123)
# => "123!!!!!!!"

Left justified

python


print "{:>10}".format("python")
# => "    python"

print "{:0>10}".format(123)
# => "0000000123"

Left and right packing

python


print "{:^10}".format("python")
# => "  python  "

print "{:#^10}".format('python')
# => "##python##"

Other string method examples

String methods (2.7.x) String method (3.5.1)

python


print '1'.zfill(5)
# => 00001
print '1'.rjust(5)
# =>     1
print '1'.ljust(5)
# => 1    
print 'python'.center(10, '#')
# => ##python##

Linking

format "This string formatting method is a new standard in Python 3.0, and new code is better than formatting with% as specified in string formatting operations." [^ 1]

python


print ('address:{city},{state},{country}'.format(city='Osaka-shi', state='Osaka', country='Japan'))
# => address:Osaka-shi,Osaka,Japan

print ('address:{0},{1},{2}'.format('Osaka-shi', 'Osaka', 'Japan'))
# => address:Osaka-shi,Osaka,Japan

[^ 1]: String method (str.format)

Recommended Posts

Various character string operations
Various Python built-in string operations
Character range / character string range
Various Numpy operations (correction)
Summary of string operations
BLAST result-like character string display
Date and time ⇔ character string
Python f character (formatted string)
Is it a character string operation?
[Shell] Various patterns of string decomposition
Summary of various operations in Tensorflow
Python UTC ⇔ JST, character string (UTC) ⇒ JST conversion memo
# 5 [python3] Extract characters from a character string
[Python] How to invert a character string
[Python beginner memo] Python character string, path operation
[Pandas] Expand the character string to DataFrame
Basic grammar of Python3 system (character string)
Python basic course (4 numeric type / character string type)
[PowerShell] Get the reading of the character string