[英]how replace every successive character in string with ‘#’ with python?
示例 - 對於給定的字符串“Hello World”,返回的字符串是“H#l#o W#r#d”。
我嘗試了此代碼,但其中也包含空格。 我希望在單詞之間保持空格
def changer():
ch=[]
for i in 'Hello World':
ch.append(i)
for j in range(1,len(ch),2):
ch[j]= '#'
s=''
for k in ch:
s=s+k
print(s)
changer()
Output - H#l#o#W#r#d
Output i want = H#l#o W#r#d
您可以在空格上str.split
以獲取子字符串,然后為每個 substring 用'#'
替換所有奇數字符,同時保留偶數字符。 然后str.join
被替換的子字符串重新組合在一起。
>>> ' '.join(''.join('#' if v%2 else j for v,j in enumerate(i)) for i in s.split())
'H#l#o W#r#d'
您可以控制增量,默認為 2,但如果有空格 1 跳過它並繼續評估下一個單詞
def changer():
ch=[]
increment = 2
for i in 'Hello World':
ch.append(i)
for j in range(1,len(ch),increment):
if not ch[j].isspace():
ch[j]= '#'
increment = 2
else:
increment = 1
s=''
for k in ch:
s=s+k
print(s)
changer()
既然您說您不想在 output 中包含空格,請不要包含它們:
ch=[]
for i in 'Hello World':
ch.append(i)
for j in range(1,len(ch),2):
if ch[j] != " ": # don't 'include' spaces
ch[j]= '#'
s=''
for k in ch:
s=s+k
print(s)
這里有很多非常不一致的答案。 我認為我們需要更多信息才能為您提供您期望的解決方案。 你能給出一個包含更多單詞的字符串來確認你想要的 output。 你說你希望每個連續的字符都是一個#,並舉了一個 H#l#o W#r#d 的例子。 您是否希望在確定下一個字符應該是什么時包含空格? 還是應該寫入空格,但跳過作為下一個字符的決定因素? 另一個選項是 'H#l#o #o#l#',其中空格包含在新文本中,但在確定下一個字符時會被忽略。
一些答案給出了這樣的信息:
string = "Hello World 這是一個測試"
'H#l#o W#r#d T#i# I# AT#s#'
'H#l#o W#r#d T#i# #s AT#s#'
'H#l#o W#r#d T#i# I# AT#s# '
此代碼給出 output:'H#l#o W#r#d T#i# #s AT#s#'
string = 'Hello World This Is A Test'
solution = ''
c = 0
for letter in string:
if letter == ' ':
solution += ' '
c += 1
elif c % 2:
solution += "#"
c += 1
else:
solution += letter
c += 1
如果您確實想要在包含空格的情況下獲得所需的結果,但不讓它們成為確定下一個字符的因素,那么您需要做的就是首先刪除計數器檢查,以便空格不會影響繼承。 解決方案是:'H#l#o #o#l# T#i# I# A #e#t'
您可以使用 itertools 中的累積來逐步構建結果字符串
from itertools import accumulate
s = "Hello World"
p = "".join(accumulate(s,lambda r,c:c if {r[-1],c}&set(" #") else "#"))
print(p)
使用您的算法,您可以單獨處理每個單詞,這樣您就不會遇到空格問題。 這是您的算法的改編版,其中每個單詞在處理后都連接到一個字符串:
my_string = 'Hello World'
my_processed_string = ''
for word in my_string.split(' '):
ch = []
for i in word:
ch.append(i)
for j in range(1, len(ch), 2):
ch[j] = '#'
for k in ch:
my_processed_string += k
my_processed_string += ' '
您可以維護一個單獨的空白計數並檢查其最低位,根據偶數或奇數將字符替換為 hash。
def changer():
ch=[]
count = 0 # hash even vals (skips 0 because count advanced before compare)
for c in 'Hello World':
if c.isspace():
count = 0 # restart count
else:
count += 1
if not count & 1:
c = '#'
ch.append(c)
s = ''.join(ch)
print(s)
changer()
結果
H#l#o W#r#d
我沒有對您的代碼進行太多更改。 所以我認為這對你來說可能很容易理解。
enter code here
def changer():
ch=[]
h='Hello World' #I have put your string in a variable
for i in h:
ch.append(i)
for j in range(1,len(ch),2):
if h[j]!=' ':
ch[j]= '#'
s=''
for k in ch:
s=s+k
print(s)
changer()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.