Putting same character in two different position in a string - python

I have an input string 'java'. I want to replace only 2 '-'s in '----' with 'a' (I want them positioned in their right index) so that I have -a-a.
How do I achieve this?

Not sure exactly what you want, but from the description you can try something like this.
keyString = "java"
targetString = ""
for i in range(len(keyString)):
if keyString[i] == 'a': targetString += 'a'
else: targetString += '-'

Sorry if I misinterpret your question. I am reading the description as "I am given an input string and need to create another string that replaces all non-'a' characters in the input string with '-'.
The most straight-forward way to do this is to iterate through the input string and build the new string as you go, concatenating either a '-' or a 'a' to the new string depending on the current character in the input string. See below...
# The given input string and the start of the new string that we will create
inputString = "java"
newString = ""
# Go through each character in the input string to determine
# which character to add to the new string at each position
for character in inputString:
if character == 'a':
newString += 'a'
else:
newString += '-'

Related

How do I change the order of recognized characters in CRNN networks(python)

I have been searching for a long time on the Internet, but to no avail. Please, I need help or some ideas about how to achieve this. For example, the recognition character is apple, so if I want to put the "A" in apple at the end of the word, like "pplea":
a-p-p-l-e ==> pplea
I don't know where to modify it, is it from the encoding or the decoding? If so, how should it be modified?
The following may help:
word = "apple"
def word_converter():
word2 = word + word[0]
word3 = word2[1:]
print(word3)
word_converter()
is simple using string position index
string = "apple"
#save fist char in one variable
first_char = string[0]
#remove first char of a string
string = string[1:]
#append first char of old string at the end of my new string
string = string + first_char
#print the result
print(string)
Its very simple. read string indexing in python
word = 'apple'
encoded = word[1:] + word[0]
print(encoded)

Print a string without any other characters except letters, and replace the space with an underscore

I need to print a string, using this rules:
The first letter should be capital and make all other letters are lowercase. Only the characters a-z A-Z are allowed in the name, any other letters have to be deleted(spaces and tabs are not allowed and use underscores are used instead) and string could not be longer then 80 characters.
It seems to me that it is possible to do it somehow like this:
name = "hello2 sjsjs- skskskSkD"
string = name[0].upper() + name[1:].lower()
lenght = len(string) - 1
answer = ""
for letter in string:
x = letter.isalpha()
if x == False:
answer = string.replace(letter,"")
........
return answer
I think it's better to use a for loop or isalpha () here, but I can't think of a better way to do it. Can someone tell me how to do this?
For one-to-one and one-to-None mappings of characters, you can use the .translate() method of strings. The string module provides lists (strings) of the various types of characters including one for all letters in upper and lowercase (string.ascii_letters) but you could also use your own constant string such as 'abcdef....xyzABC...XYZ'.
import string
def cleanLetters(S):
nonLetters = S.translate(str.maketrans('','',' '+string.ascii_letters))
return S.translate(str.maketrans(' ','_',nonLetters))
Output:
cleanLetters("hello2 sjsjs- skskskSkD")
'hello_sjsjs_skskskSkD'
One method to accomplish this is to use regular expressions (regex) via the built-in re library. This enables the capturing of only the valid characters, and ignoring the rest.
Then, using basic string tools for the replacement and capitalisation, then a slice at the end.
For example:
import re
name = 'hello2 sjsjs- skskskSkD'
trans = str.maketrans({' ': '_', '\t': '_'})
''.join(re.findall('[a-zA-Z\s\t]', name)).translate(trans).capitalize()[:80]
>>> 'Hello_sjsjs_skskskskd'
Strings are immutable, so every time you do string.replace() it needs to iterate over the entire string to find characters to replace, and a new string is created. Instead of doing this, you could simply iterate over the current string and create a new list of characters that are valid. When you're done iterating over the string, use str.join() to join them all.
answer_l = []
for letter in string:
if letter == " " or letter == "\t":
answer_l.append("_") # Replace spaces or tabs with _
elif letter.isalpha():
answer_l.append(letter) # Use alphabet characters as-is
# else do nothing
answer = "".join(answer_l)
With string = 'hello2 sjsjs- skskskSkD', we have answer = 'hello_sjsjs_skskskSkD';
Now you could also write this using a generator expression instead of creating the entire list and then joining it. First, we define a function that returns the letter or "_" for our first two conditions, and an empty string for the else condition
def translate(letter):
if letter == " " or letter == "\t":
return "_"
elif letter.isalpha():
return letter
else:
return ""
Then,
answer = "".join(
translate(letter) for letter in string
)
To enforce the 80-character limit, just take answer[:80]. Because of the way slices work in python, this won't throw an error even when the length of answer is less than 80.

Cut a substring from the end until the first occurrence of a certain character

I have a string lets say something like below:
abc$defg..hij/klmn
How can I get substring which is cut out from last character until we encounter the $ sign. Note $ could be a special character and there could other special characters in the string.
The output should be:
defg..hij/klmn
I a using python 2.7 and above.
That is an alternate method. It checks each character from the end until a special character is met.
text = "abc$defg..hij/klmn"
newstring = text[::-1]
output = ""
for character in newstring:
if character != "$":
output += character
else:
break
print(output[::-1])
You could use the split function:
your_string = "abc$defg..hij/klmn"
split_char = "$"
substring = your_string.split(split_char)[-1]
You'll need to first get the occurrence of that first character and then slice from that index plus 1:
testStr = "abc$defg..hij/klmn"
try:
index = testStr.index()
start = index + 1
print(str[start:])
except:
print("Not in string")
Note: This will return a single string from after the first & to the end. If you want multiple strings enclosed within $, the accepted answer works well.

Letter Capitalize not working in every case

I just started to learn python a few months ago so I'm a newbie here. I was trying to capitalize the first letter of every word in a string. When the input is "hello world" (for example) it works perfectly, but with some inputs like "i love coding" it returns this "I Love CodIng" and it just doesn't make sense to me. Could someone explain to me why this is happening? Here's the code:
def LetterCapitalize(str):
str = str.replace(str[0], str[0].upper())
for i in range(len(str)):
try:
if str[i] == ' ':
str = str.replace(str[i+1], str[i+1].upper())
else:
continue
except IndexError:
break
return str
The str.replace method replaces all occurrences of the given substring in the given main string, so by replacing the letter i with I in i love coding it replaces both is in the string.
Since strings are immutable you can instead convert the given string to a list of characters, so that you can iterate through the list, replace the character if it's either at the start of the string or preceded by a space, and join the list back to a string in the end:
def LetterCapitalize(s):
l = list(s)
for i, c in enumerate(l):
if not i or l[i - 1] == ' ':
l[i] = c.upper()
return ''.join(l)
so that LetterCapitalize('i love coding') returns:
I Love Coding
The problem with the code is your first line,
str = str.replace(str[0], str[0].upper())
Here you replace first letter with its capital, but also you replace that letter in all the following string.
Example :
LetterCapitalize("hello hoher") -> 'Hello HoHer'
You need to modify single character at a given position in the string and not replace all the occurring letters. You should try to work with string as a list. Here is a helpful link : Change one character in a string?

How to swap values in strings without loop

string = input('Please enter a string: ')
replaced_string = string.replace(string[0],'e')
replaced_string[0] = string[0]
print(replaced_string)
I tried to replace all the letters of the first char in the string but keep the first char as it was, but apparently my code doesn't work on the third line. Can you suggest a solution how to replace it?
You could do it like this:
input_str = input()
first_letter = input_str[0]
rest_of_letters = input_str[1:]
# Take the first letter, and append it the rest of the letters, but
# with "e" replaced by the first letter.
replaced_string = first_letter + rest_of_letters.replace(first_letter, 'e')
The key problem with how you tried to do it is strings are immutable. You can't do my_str[0] = "a". If you want to modify a string you must create a new string with the modifications you want.
I am not getting what you want to do. but Strings do not support item assignment.

Categories

Resources