[英]How To Remove Quotes From String in Python
目前,我有一個字符串列表,可以說:
list1 = [1,2,3,4]
我想使用以下方法將此數字列表轉換為相應的字母:
output = [chr(ord((str(x+96)))) for x in list1]
這樣做時,我收到一條錯誤消息,說程序期望字符串長度為1,但是在我的代碼中,由於將數字轉換為字符串后每個數字都帶有''
,所以給出的字符串長度為3。 必須轉換為字符串,因為必須采用字符串格式才能使ord正常工作。
所以我對你們的問題是,如何解決這個問題和/或擺脫這些引用?
萬一有人想知道,它應該以
output = [a,b,c,d]
您有一個整數,將其添加96,結果應為:
output = [chr(x+96) for x in list1]
您可以完全ord
和str
。
list1 = [1,2,3,4]
output = [chr(x+96) for x in list1]
print output #Prints: ['a', 'b', 'c', 'd']
您的答案將類似於:
output = [chr((x+96)) for x in list1]
ord
接受一個字符並返回該字符的整數序數。 在您的代碼中,您正在執行:
ord((str(x+96)))
就像
ord((str(1+96)))
ord('97')
所以你得到了錯誤。 ord
的參數將是一個字符串。 喜歡:
>>> ord('a')
>>> 97
但是,要獲得預期的輸出,您無需使用ord
。
打印列表會打印其元素的字符串表示形式,其中包括列表內字符串元素周圍的單引號。 而是自己格式化字符串:
>>> '[{}]'.format(','.join([chr((x+96)) for x in list1]))
'[a,b,c,d]'
或以印刷形式:
>>> print '[{}]'.format(','.join([chr((x+96)) for x in list1]))
[a,b,c,d]
format
方法允許您格式化字符串。 在這種情況下,花括號用作要包含在最終字符串中的值的占位符。 方括號是提供實際的類似數組輸出的格式的一部分。 join
方法采用對象數組並將它們連接在一起以形成單個組合字符串。 在這種情況下,我使用文字逗號連接了多個對象。 這將產生一個逗號分隔的字符串輸出。 內部列表理解本質上是您已經提供的代碼。
你不能只是這樣做的理智方法嗎
string = " abcdefghijklmnopqrstuvwxyz"
newlist = []
for num in nums:
newlist.append(string[num])
假設您只想打印一個字符串:
>>> list1 = [1, 2, 3, 4]
>>> pretty_string = ""
>>> # strings are immutable so need to
>>> # create new and assign to old variable name.
>>> for i in list1:
>>> pretty_string = pretty_string + str(i) + ", "
>>> pretty_string = pretty_string[:-2] # remove trailing comma and space
>>> print(pretty_string)
1, 2, 3, 4
str(i)
方法將i
轉換為字符串類型
或者,逐字打印您要問的內容:
>>> print("output = [" + pretty_string + "]")
output = [1, 2, 3, 4]
但是,如果您想要一個整數列表元素的字符表示列表,則:
>>> list1 = [1, 2, 3, 4] # integer values
>>> character_reps = []
>>> for i in list1:
>>> character_reps.append(str(i))
>>> for i in character_reps:
>>> print(i) # no need to convert as members already string types
1
2
3
4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.