Can you cast a string to upper case while formating - python

Motivation
Suppose you have a string that is used twice in one string. However, in one case it is upper, and the other it is lower. If a dictionary is used, it would seem the solution would be to add a new element that is uppercase.
Suppose I have a python string ready to be formatted as:
string = "{a}_{b}_{c}_{a}"
With a desired output of:
HELLO_by_hi_hello
I also have a dictionary ready as:
dictionary = {a: "hello", b: "bye", c: "hi"}
Without interacting with the dictionary to set a new element d as being "HELLO" such as:
dictionary['d'] = dictionary['a'].upper()
string = "{d}_{b}_{c}_{a}"
string.format(**dictionary)
print(string)
>>> HELLO_bye_hi_hello
Is there a way to set element a to always be uppercase in one case of the string? For example something like:
string= "{a:upper}_{b}_{c}_{a}"
string.format(**dictionary)
print(string)
>>> HELLO_bye_hi_hello

Yes, you can do that:
string = "{d.upper()}_{b.lower()}_{c.lower()}_{a.lower()}"

Nope, you can't do that.
In the simplest solution, you can write a lambda to capitalize the values in your string. Or you can subclass strnig.Formatter if you really want to achieve your goal that way.
Following link can help if you are going for the harder method.
Python: Capitalize a word using string.format()

Related

format only subscript first letter (python)

I have this symbolic variable below (b). For some reason only the first letter of the word 'front' appears in the subscript rather than the entire word.
Code:
a = 'front'
b = sym.symbols('\\theta{{A}}_{0}'.format(a))
Output:
𝜃𝐴𝑓𝑟𝑜𝑛𝑡
where only the letter 'f' is appears in the subscript. I've tried the alternative of:
b = sym.symbols('\\theta{{A}}_{0}'.format({a}))
which subscripts the entire word but the word has inverted commas when being displayed. Could anyone provide some idea of why it's happening and how I could fix it?
The string after formatting becomes:
>>> a = "front"
>>> '\\theta{{A}}_{0}'.format(a)
'\\theta{A}_front'
Which should help explain the issue here. As you can imagine, this only turns the f into a subscript.
What you need is '\\theta{{A}}_{{{0}}}'.format(a):
>>> '\\theta{{A}}_{{{0}}}'.format(a)
'\\theta{A}_{front}'
In Python's format strings, {0} denotes the first place where a substitution can be performed with .format, while {{ and }} simply become { and } respectively after using .format. Hence, you need {{{0}}}.format(a) to get {front} as output.

Using functions how to split a string by coma "," and remove single space space and if 2 consecutive occurs replace it with single.

I have a question that ask the user to input a string THE and split it as three different string, output like this T,H,E I tried but output same with input.
def func():
str1=input("Enter String : ")
','.split(str1)
print(str1)
func()
Output
THE
And second question is that ask the user to enter a string T H E S T R I N G and the output should THE STRING when one space occurs remove it and if more then one then replace it whit single space.
Here is my code.
def func2():
str2=input("Enter String :")
for i in str2:
if(i.isspace==True):
del(i)
else:
str2=str2+i
print(str2)
func2()
output is.
T H E S T R I N GTHESTRING
I have no idea how to correct it.
You cannot store the value after splitting and not printing it.
Just change ','.split(str1) with str1 =str1.split(',') and print str1.
Read the documentation for the split method: it doesn't apply to your first problem at all. Instead, the solution is much simpler: take the individual characters and join them with commas:
char_list = list(str1)
str2 = ','.join(char_list)
... and print or return str3. Yes, this can be shortened; I'm teaching you the individual steps.
As the posting guidelines tell you, each question must have a separate posting. I'll leave the other answer for your other posting.
There's a distinction between in-place and standard operators. In-place functions actually change in the input, while standard operators give a result as output, and that output then has to be assigned or passed to something else for it to be used. (Also, you don't have the syntax correct; it should be 'str1.split(',')) The split operator is a standard operator; 'str1.split(',') doesn't affect the value of str1, but instead creates a new result. Since you're not doing anything with that result, it gets thrown away. You could do split_string ='str1.split(',') and then print(new_string) or just print('str1.split(',').
Also, the problem statements "split it as three different string" and "output like this T,H,E" are contradictory. If you want a list of three strings, that would be ['T','H','E']. Saying you want an output of T,H,E makes it sound like you want a single string with commas between the letters.

Python 3, receive a string as an argument without any return value

I'm learning Python and have been taking an online class. This class was very basic and I am know trying to continue my studies elsewhere. Stackoverflow.com has helped me a great deal. In the online course we didn't cover a lot about return statements, which I am now trying to learn. I would like to do something very basic, so I was thinking of creating a program that would receive a string as an argument without having any return value. I want the user to type a word that will be shown with characters or symbols between every letter.
Example
User types in the word Python.
The word will be shown as =P=y=t=h=o=n= or -P-y-t-h-o-n- or maybe with * between every letter.
Is this an easy task? Can someone help me how to go about doing this?
Thank you.
Joel
If you want to do it yourself, you can go through your string like this:
my_string = "Python"
for letter in my_string:
# do something with the letter
print(letter)
This will print each letter in your word. What you want to do is having a new string with your desired character. You probably know you can concatenate (append) two strings in this way :
str1 = "hello"
str2 = "world"
str3 = str1 + str2
print(str3) #helloworld
So to do what you'd like to do, you can see each letter as a substring of your main string, and your desired character (for example *) as another string, and build a result string in that way.
inputString = "Python"
result = ""
myChar = "*"
for letter in inputString:
# build your result
build = build + letter
print(build)
This will just copy inputString into result, though I think you'll have understood how to use it in order to add your custom chars between the letters.
Yes python makes this sort of string manipulation very easy (some other languages... not so much). Look up the standard join function in the python docs.
def fancy_print(s, join_char='-'):
# split string into a list of characters
letters = list(s)
# create joined string
output = join_char + join_char.join(letters) + join_char
# show it
print(output)
then
>>> fancy_print("PYTHON")
-P-Y-T-H-O-N-
>>> fancy_print("PYTHON", "*")
*P*Y*T*H*O*N*

Reassigning letters in an alphet to a higher letter in python?

If I am building a basic encryption program in python that reassigns A to C and D to F and so on, what is a simple algorithm I could use to do this?
I have a list named alphabet that holds each letter, then a variable that takes in the user input to change to the encrypted version.
str.translate should be the easiest way:
table = str.maketrans(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
"cdefghijklmnopqrstuvwxyzabCDEFGHIJKLMNOPQRSTUVWXYZAB"
)
s = "Test String"
print(s.translate(table))
Output:
Vguv Uvtkpi
There's two major parts to this. First, ciphering a single letter; and second, applying that to the whole string. We'll start with the first one.
You said you had a list with the alphabet in it. Suppose, too, that we have a letter.
>>> letter = 'F'
If we want to replace that letter with the letter two spaces down in the alphabet, first we'll probably want to find the numerical value of that letter. To do that, use index:
>>> alphabet.index(letter)
5
Next, you can add the offset to it and access it in the list again:
>>> alphabet[alphabet.index(letter) + 2]
'H'
But wait, this won't work if we try doing a letter like Z, because when we add the index, we'll go off the end of the list and get an error. So we'll wrap the value around before getting the new letter:
>>> alphabet[(alphabet.index('Z') + 2) % len(alphabet)]
'B'
So now we know how to change a single letter. Python makes it easy to apply it to the whole string. First putting our single-letter version into a function:
>>> def cipher_letter(letter):
... return alphabet[(alphabet.index(letter) + 2) % len(alphabet)]
...
We can use map to apply it over a sequence. Then we get an iterable of ciphered characters, which we can join back into a string.
>>> ''.join(map(cipher_letter, 'HELLOWORLD'))
'JGNNQYQTNF'
If you want to leave characters not in alphabet in place, add a test in cipher_letter to make sure that letter in alphabet first, and if not, just return letter. Voilà.

String tokenization python

I wanted to split a string in python.
s= "ot.jpg/n"
I used str.split() but it gives me ['ot.jpg']. I want to get ot.jpg without brackets.
You want to use str.strip() to get rid of the newline. If you need to use split, it returns a list. To get the nth item from a list, index the list: ['foo', 'bar'][n].
Incidentally, naming your string str is a bad idea, since it shadows the built-in str function.
The return value of the split() method is always a list -- in this case, it's given you a single-element list theList = ['ot.jpg']. Like any list, you get what you want out of it by indexing it:
myString = theList[0]
sounds like you want replace.
s= "ot.jpg/n".replace("/n", "")
"ot.jpg"

Categories