Can a variable be passed to format() to pad? - python

With new-style formatting, we can do:
In [262]: '{:_>10}'.format('test')
Out[262]: '______test'
Instead of the underscore (or whatever character), can this be replaced by a variable? So if:
double_dashes = '--'
Can we somehow incorporate this variable in call to format() so we get:
--------------------test

Instead of the underscore (or whatever character), can this be replaced by a variable?
Yes, that is fairly easy using a nested {}:
>>> '{:{}>10}'.format('test', 'x')
'xxxxxxtest'
Can we somehow incorporate this variable in call to format() so we get:
--------------------test
No. The fill character string must only be one character long.

Related

strings inside python template- and f-strings

Could someone please break down why "{dic['string_key']}".format(dic=dic) considers the single quotations to be part of the string-key and does a lookup under dic["'string_key'"] ?
a) and b) show the correct way, however I am missing the reason.
a = "{dic[string_key]}"
print(a.format(dic=dic))
b = f"{dic['string_key']}"
print(b)
format and f-strings use braces differently.
With str.format, the contents of the braces are part of a mini-language used by format to substitute its arguments into the format string.
In an f-string, it's an arbitrary Python expression to evaluate.
In this case:
a = "{dic[string_key]}"
print(a.format(dic=dic))
... the string is formatted when .format() is called and that function uses a formatting language that is documented here https://docs.python.org/3/library/string.html#formatstrings.
But in this case:
b = f"{dic['string_key']}"
print(b)
... the string is formatted when the assignment to b is executed, by Python itself. The expression inside the f-string follows normal Python syntax, with the exception that you cannot reuse the quotes used to enclose the f-string.
As a result, you need to specify the quotes around the dictionary key as you would normally, while the mini-language for .format() expects you to omit them.
Also note that this makes a lot of sense: b = f"{dic[string_key]}" should use the value of the variable string_key to index the dictionary.

Remove "." and "\" from a string

my project is to capture a log number from Google Sheet using gspread module. But now the problem is that the log number captured is in the form of string ".\1300". I only want the number in the string but I could not remove it using the below code.
Tried using .replace() function to replace "\" with "" but failed.
a='.\1362'
a.replace('\\',"")
Should obtain the string "1362" without the symbol.
But the result obtained is ".^2"
The problem is that \136 has special meaning (similar to \n for newline, \t for tab, etc). Seemingly it represents ^.
Check out the following example:
a = '.\1362'
a = a.replace('\\',"")
print(a)
b = r'.\1362'
b = b.replace('\\',"")
print(b)
Produces
.^2
.\1362
Now, if your Google Sheets module sends .\1362 instead of .\\1362, if is very likely because you are in fact supposed to receive .^2. Or, there's a problem with your character encoding somewhere along the way.
The r modifier I put on the b variable means raw string, meaning Python will not interpret backlashes and leave your string alone. This is only really useful when typing the strings in manually, but you could perhaps try:
a = r'{}'.format(yourStringFromGoogle)
Edit: As pointed out in the comments, the original code did in fact discard the result of the .replace() method. I've updated the code, but please note that the string interpolation issue remains the same.
When you do a='.\1362', a will only have three bytes:
a = '.\1362'`
print(len(a)) # => 3
That is because \132 represents a single character. If you want to create a six byte string with a dot, a slash, and the digits 1362, you either need to escape the backslash, or create a raw string:
a = r'.\1362'
print(len(a)) # => 6
In either case, calling replace on a string will not replace the characters in that string. a will still be what it was before calling replace. Instead, replace returns a new string:
a = r'.\1362'
b = a.replace('\\', '')
print(a) # => .\1362
print(b) # => .1362
So, if you want to replace characters, calling replace is the way to do it, but you've got to save the result in a new variable or overwrite the old.
See String and Bytes literals in the official python documentation for more information.
Your string should contains 2 backslashes like this .\\1362 or use r'.\1362' (which is declaring the string as raw and then it will be converted to normal during compile time). If there is only one backslash, Python will understand that \136 mean ^ as you can see (ref: link)
Whats happening here is that \1362 is being encoded as ^2 because of the backslash, so you need to make the string raw before you're able to use it, you can do this by doing
a = r'{}'.format(rawInputString)
or if you're on python3.6+ you can do
a = rf'{rawInputString}'

Changing string to uppercase in python

I' trying to change my variable to uppercase and I don't know what I'm getting wrong. Sample code:
Quacks = "time"
Quacks.upper()
print(Quacks)
When I run the above code, time is returned instead of TIME.
Method upper() does not change the value of variable, it only returns a string where all characters are in upper case.
So, you may print it directly:
print(Quacks.upper())
or change first and then print:
Quacks = Quacks.upper()
print(Quacks)
In Python str.upper() returns a copy of the string with upper case values, and does not mutate the original string. In fact, strings in Python are immutable anyways.
Try: Quacks = Quacks.upper()
Source: https://docs.python.org/3/library/stdtypes.html
"str.upper() - Return a copy of the string with all the cased characters [...] converted to uppercase."

Increasing understanding of the formatting in Python with the format() function

hilarious = False
joke_evaluation = "Isn't that joke so funny?! {}"
print(joke_evaluation.format(hilarious))
For the following lines of Python code I'm failing to understand a key concept.
A string is assigned to the variable joke_evaluationand include {} to embed another variable within it.
The third line of code has got me stuck, we are saying print the variable joke_evaluation then using the .format() function and passing another variable to it - hilarious which is set as a boolean data type.
Are the {} effectively functioning as placeholders? How does the .format() function know to populate the {} with the variable hilarious?
Please explain in basic terms if possible to increase my understanding, I'm failing to understand how Python populates the curly braces {} as I've mentioned above.
Here's my understanding of the the format method:
Any string with curly braces {} will be replaced with the variable you have provided. So, if I have a string say:
myStr = "hello {}"
then doing:
res = myStr.format("user")
print(res) #prints "hello user" without quotes.
Now, doing this:
res = myStr.format(123123)
print(res) #prints "hello 123123" without quotes.
As you might have guessed, the integer 123123 was implicitly converted to string before being included in the string.
Now, coming to the curly {} part:
You can have multiple curly braces and must have the same number of parameters passed to format method. Eg:
myStr = "hello {},{},{}, nice meeting you"
res = myStr.format("abcd",123,"lol")
print(res) #prints "hello abcd,123,lol, nice meeting you"
You can even put indices in the {} to indicate position like {0} and {1}.
Yes, {} acting as placeholders, which is treated by .format method in special way.
How does the .format() function know to populate the {} with the variable hilarious?
If you're providing {} only, it's substituted position-wise, i.e.
>>> 'first: {}, second: {}'.format(1, 2)
'first: 1, second: 2'
For more verbose or re-usable substitution you can use named arguments:
>>> "{actor1} tells {actor2} that he's {actor1}".format(actor1='Bob', actor2='Joel')
"Bob tells Joel that he's Bob"
More on awesome string formatting: pyformat.info
A bit more on formatting, when .format substituting placeholders with some objects, it calls __format__ method on it, which
Accepts formatting spec — which gives you ability to control how it will be converted (for example, '{:.2f}'.format(3.1415)
Return str, which will actually substitute placeholders
Read Python documentation about string: https://docs.python.org/3.6/library/string.html?highlight=formatting
:) Everything you need to know. You can also change Python versions and see the behavior of formatting.
Scroll down to see examples and explanations.

Print raw string from variable? (not getting the answers)

I'm trying to find a way to print a string in raw form from a variable. For instance, if I add an environment variable to Windows for a path, which might look like 'C:\\Windows\Users\alexb\', I know I can do:
print(r'C:\\Windows\Users\alexb\')
But I cant put an r in front of a variable.... for instance:
test = 'C:\\Windows\Users\alexb\'
print(rtest)
Clearly would just try to print rtest.
I also know there's
test = 'C:\\Windows\Users\alexb\'
print(repr(test))
But this returns 'C:\\Windows\\Users\x07lexb'
as does
test = 'C:\\Windows\Users\alexb\'
print(test.encode('string-escape'))
So I'm wondering if there's any elegant way to make a variable holding that path print RAW, still using test? It would be nice if it was just
print(raw(test))
But its not
I had a similar problem and stumbled upon this question, and know thanks to Nick Olson-Harris' answer that the solution lies with changing the string.
Two ways of solving it:
Get the path you want using native python functions, e.g.:
test = os.getcwd() # In case the path in question is your current directory
print(repr(test))
This makes it platform independent and it now works with .encode. If this is an option for you, it's the more elegant solution.
If your string is not a path, define it in a way compatible with python strings, in this case by escaping your backslashes:
test = 'C:\\Windows\\Users\\alexb\\'
print(repr(test))
In general, to make a raw string out of a string variable, I use this:
string = "C:\\Windows\Users\alexb"
raw_string = r"{}".format(string)
output:
'C:\\\\Windows\\Users\\alexb'
You can't turn an existing string "raw". The r prefix on literals is understood by the parser; it tells it to ignore escape sequences in the string. However, once a string literal has been parsed, there's no difference between a raw string and a "regular" one. If you have a string that contains a newline, for instance, there's no way to tell at runtime whether that newline came from the escape sequence \n, from a literal newline in a triple-quoted string (perhaps even a raw one!), from calling chr(10), by reading it from a file, or whatever else you might be able to come up with. The actual string object constructed from any of those methods looks the same.
I know i'm too late for the answer but for people reading this I found a much easier way for doing it
myVariable = 'This string is supposed to be raw \'
print(r'%s' %myVariable)
try this. Based on what type of output you want. sometime you may not need single quote around printed string.
test = "qweqwe\n1212as\t121\\2asas"
print(repr(test)) # output: 'qweqwe\n1212as\t121\\2asas'
print( repr(test).strip("'")) # output: qweqwe\n1212as\t121\\2asas
Get rid of the escape characters before storing or manipulating the raw string:
You could change any backslashes of the path '\' to forward slashes '/' before storing them in a variable. The forward slashes don't need to be escaped:
>>> mypath = os.getcwd().replace('\\','/')
>>> os.path.exists(mypath)
True
>>>
Just simply use r'string'. Hope this will help you as I see you haven't got your expected answer yet:
test = 'C:\\Windows\Users\alexb\'
rawtest = r'%s' %test
I have my variable assigned to big complex pattern string for using with re module and it is concatenated with few other strings and in the end I want to print it then copy and check on regex101.com.
But when I print it in the interactive mode I get double slash - '\\w'
as #Jimmynoarms said:
The Solution for python 3x:
print(r'%s' % your_variable_pattern_str)
Your particular string won't work as typed because of the escape characters at the end \", won't allow it to close on the quotation.
Maybe I'm just wrong on that one because I'm still very new to python so if so please correct me but, changing it slightly to adjust for that, the repr() function will do the job of reproducing any string stored in a variable as a raw string.
You can do it two ways:
>>>print("C:\\Windows\Users\alexb\\")
C:\Windows\Users\alexb\
>>>print(r"C:\\Windows\Users\alexb\\")
C:\\Windows\Users\alexb\\
Store it in a variable:
test = "C:\\Windows\Users\alexb\\"
Use repr():
>>>print(repr(test))
'C:\\Windows\Users\alexb\\'
or string replacement with %r
print("%r" %test)
'C:\\Windows\Users\alexb\\'
The string will be reproduced with single quotes though so you would need to strip those off afterwards.
To turn a variable to raw str, just use
rf"{var}"
r is raw and f is f-str; put them together and boom it works.
Replace back-slash with forward-slash using one of the below:
re.sub(r"\", "/", x)
re.sub(r"\", "/", x)
This does the trick
>>> repr(string)[1:-1]
Here is the proof
>>> repr("\n")[1:-1] == r"\n"
True
And it can be easily extrapolated into a function if need be
>>> raw = lambda string: repr(string)[1:-1]
>>> raw("\n")
'\\n'
i wrote a small function.. but works for me
def conv(strng):
k=strng
k=k.replace('\a','\\a')
k=k.replace('\b','\\b')
k=k.replace('\f','\\f')
k=k.replace('\n','\\n')
k=k.replace('\r','\\r')
k=k.replace('\t','\\t')
k=k.replace('\v','\\v')
return k
Here is a straightforward solution.
address = 'C:\Windows\Users\local'
directory ="r'"+ address +"'"
print(directory)
"r'C:\\Windows\\Users\\local'"

Categories