I just want to know if this is a good way or not.
Input_str = "random Str"
Output_str = ""
for i in range(len(Input_str)+1):
if i == 0: continue
Output_str += Input_str[-i]
print(Output_str)
To quickly reverse a string use the following code:
string = "string"
string[::-1]
>>> gnirts
It takes the entire string and iterates reversely over it .
There is a better and more pythonistic way to do this (although your code works just fine).
output_str = input_str[::-1]
This will pretty much do exactly what your code does - it will iterate from the end of the string towards the front and save that reversed string into the new variable.
You can read more about this syntax called string slicing here.
Related
I want to loop through a string and when it finds an uppercase letter, I want to replace it with #. Like this:
string = "hOw Are yOu?"
for x in string:
if x.isupper():
string.replace(x, "#")
print(string)
else:
print(string)
However, its not working as intended and is instead outputting the same string. Do tell me if there is a way to fix this or if you'd suggest another way.
Use list comprehension with join:
In [4]: ''.join([i if not i.isupper() else '#' for i in string])
Out[4]: 'h#w #re y#u?'
You just want to put the result again in string see below
string = "hOw Are yOu?"
for x in string:
if x.isupper():
string = string.replace(x, "#")
print(string)
else:
print(string)
Strings are immutable in Python. string.replace(x, "#") must thus be string = string.replace(x, "#") to have an effect on the string.
Note that currently your code has quadratic complexity as each replace operation has to loop over the entire string in linear time. A more efficient approach would be to perform the replacements yourself, as you're already looping over every character:
string = "".join(["#" if c.isupper() else c for c in "hOw Are yOu?"])
it would be even more concise (and possibly faster) to use a very simple RegEx for this:
import re
string = re.sub("[A-Z]", "#", "hOw Are yOu?")
this will fail for non-ASCII alphabets however; you'd have to use unicode properties & regex there.
This should do the trick!
string = "hOw Are yOu?"
for x in string:
if x.isupper():
string = string.replace(x, "#")
else:
pass
print(string)
I'm a novice as well! But from what I learned: when doing loops or if statements, you want to specify the value you are changing as I did in line 4 with: string = string.replace(x,'#') If not the change will not take effect!
Example:
my_list = [1,2,3,4]
for x in my_list:
my_list[x-1] = x + 1
print(my_list)
This is a poor example coding wise but it exemplifies the concept. If you don't address the variable it wont have any effect on it!
Hope this helps!
I just want to make an input text:
text = input('Your text: ')
And after the user types the text, I want the programme to take only capital letters from it and print them.
What does the easiest way mean? - Well, try to not use
functions, lists and stuff like that. Try to make the programme as
easy as possible. Thanks beforehand.
for char in text:
if char.isupper():
print(char)
A couple of inline ways to do it:
List comprehensions:
uppercase_chars = [char for char in text if char.isupper()]
Filter functions:
uppercase_chars = filter(str.isupper,text)
Although these answers both return lists, we can easily collapse them to strings using str.join like so:
''.join(uppercase_chars)
These are not as simple as BVB44's answer, but they're much more likely to be seen in real-world code.
Use a for loop to check if each character is uppercase, and add it to a new variable if it is. How this works is:
For every character in the variable my_string, Python checks if the character is uppercase. If it is, it adds it to the variable output. This keeps everything on one line.
my_string = input("Type some stuff ")
output = ''
for char in my_string:
if char.isupper():
output = output + char
print(output)
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*
I'm trying to find way to parse string that can contain variable, function, list, or dict written in python syntax separated with ",". Whitespace should be usable anywhere, so split with "," when its not inside (), [] or {}.
Example string: "variable, function1(1,3), function2([1,3],2), ['list_item_1','list_item_2'],{'dict_key_1': "dict_item_1"}"
Another example string: "variable,function1(1, 3) , function2( [1,3],2), ['list_item_1','list_item_2'],{'dict_key_1': "dict_item_1"}"
Example output ["variable", "function1(1,3)", "function2([1,3],2)", "['list_item_1','list_item_2']", "{'dict_key_1': "dict_item_1"}"]
edit:
Reason for the code is to parse string an then run it with exec("var = &s" % list[x]). (yes i know this might not be recommended way to do stuff)
I guess the main problem here is that the arrays and dicts also have commas in them, so just using str.split(",") wouldn't work. One way of doing it is to parse the string one character at a time, and keep track of whether all brackets are closed. If they are, we can append the current result to an array when we come across a comma. Here's my attempt:
s = "variable, function1(1,3),function2([1,3],2),['list_item_1','list_item_2'],{'dict_key_1': 'dict_item_1'}"
tokens = []
current = ""
open_brackets = 0
for char in s:
current += char
if char in "({[":
open_brackets += 1
elif char in ")}]":
open_brackets -= 1
elif (char == ",") and (open_brackets == 0):
tokens.append(current[:-1].strip())
current = ""
tokens.append(current)
for t in tokens:
print(t)
"""
variable
function1(1,3)
function2([1,3],2)
['list_item_1','list_item_2']
{'dict_key_1': 'dict_item_1'}
"""
Regular expressions aren't very good for parsing the complexity of arbitrary code. What exactly are you trying to accomplish? You can (unsafely) use eval to just evaluate the string as code. Or if you're trying to understand it without evaling it, you can use the ast or dis modules for various forms of inspection.
Have you tried using split?
>>> teststring = "variable, function1(1,3), function2([1,3],2), ['list_item_1','list_item_2'],{'dict_key_1': 'dict_item_1'}"
>>> teststring.split(", ")
['variable', 'function1(1,3)', 'function2([1,3],2)', "['list_item_1','list_item_2'],{'dict_key_1': 'dict_item_1'}"]
I have a list containing the lines of a file.
list1[0]="this is the first line"
list2[1]="this is the second line"
I also have a string.
example="TTTTTTTaaaaaaaaaabcccddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeefffff"
I want to replace list[0] with the string (example). However I want to keep the word length. For example the new list1[0] should be "TTTT TT TTa aaaaa aaaa". The only solution I could come up with was to turn the string example into a list and use a for loop to read letter by letter from the string list into the original list.
for line in open(input, 'r'):
list1[i] = listString[i]
i=i+1
However this does not work from what I understand because Python strings are immutable? What's a good way for a beginner to approach this problem?
I'd probably do something like:
orig = "this is the first line"
repl = "TTTTTTTaaaaaaaaaabcccddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeefffff"
def replace(orig, repl):
r = iter(repl)
result = ''.join([' ' if ch.isspace() else next(r) for ch in orig])
return result
If repl could be shorter than orig, consider r = itertools.cycle(repl)
This works by creating an iterator out of the replacement string, then iterating over the original string, keeping the spaces, but using the next character from the replacement string instead of any non-space characters.
The other approach you could take would be to note the indexes of the spaces in one pass through orig, then insert them at those indexes in a pass of repl and return a slice of the result
def replace(orig, repl):
spaces = [idx for idx,ch in enumerate(orig) if ch.isspace()]
repl = list(repl)
for idx in spaces:
repl.insert(idx, " ")
# add a space before that index
return ''.join(repl[:len(orig)])
However I couldn't imagine the second approach to be any faster, is certain to be less memory-efficient, and I don't find it easier to read (in fact I find it HARDER to read!) It also don't have a simple workaround if repl is shorter than orig (I guess you could do repl *= 2 but that's uglier than sin and still doesn't guarantee it'll work)